import java.util.*;
public class Hello {
public static void main(String[] args) {
ArrayList<Integer> userInput = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a list of numbers: ");
while(scan.hasNextInt())
{
userInput.add(scan.nextInt());
}
for(int userOutput : userInput)
{
for(int i = 0; i < userOutput.size(); i++)
{
if(i < userOutput.get(i))
{
System.out.println("Largest number is: " + userOutput );
}
}
}
}
}
Asked
Active
Viewed 71 times
-1
-
1In this code userOutput should be an integer. Why the second for loop is required? – Srivignesh Nov 08 '19 at 06:30
-
to get the largest number – jsbadz Nov 08 '19 at 06:42
-
[Java: Finding the highest value in an array](https://stackoverflow.com/questions/1806816/java-finding-the-highest-value-in-an-array) – Abra Nov 08 '19 at 07:01
4 Answers
2
You have to use userInput.size() since you want to know the size of the list. If you want to find the largest using a for loop :
int largest = userInput.get(0);
for(int i = 1; i < userInput.size(); i++)
{
if (largest < userInput.get(i))
{
largest = userInput.get(i);
}
}
System.out.println("Largest number is: " + largest);

Staphy Joseph
- 131
- 3
0
This is because you are calling size()
method in a primitive type data. For your case userOutput is a primitive int
type data. So you can't call .size()
in it.

Alif Hasnain
- 1,176
- 1
- 11
- 24
0
I think you are mistakenly using userOutput inplace of userInput. Here is the corrected code:
for(int i = 0; i < userInput.size(); i++)
{
if(i < userInput.get(i))
Regards, Srikanth Kondaveti

Sriko
- 1
- 1