0

Here is my program...

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    ArrayList<Integer> list = new ArrayList<>();

    while (true) {
        int number = Integer.valueOf(scanner.nextLine());
        if (number <= -1) {
            break;
        }
        list.add(number);
    }
    int biggest = list.get(0);              

    for (int i = 0; i <= list.size()-1; i++) {        
        int small = list.get(i);            
        if (small > biggest) {               
            biggest = small;
        }

    }
    System.out.println("The greatest number: " + biggest);

}

It does what the project is asking me to do. I just have to iterate through the ArrayList and print out the greatest in the list. It works! but, when I submit the project, I just get back an "Index out of bounds exception". Why does this happen?

1 Answers1

0
int number = Integer.parseInt(scanner.nextLine());

Use .parseInt() to get int value from the String. Not .valueOf() when working with primitives.

From the docs:

.valueOf() method returns an Integer object equal to the value of:

new Integer(Integer.parseInt(s))

If the first number entered is -1, then list.get(0); will throw the same exception. You need to put a check like:

if (list.size() > 0) {
    int biggest = list.get(0);

    for (int i = 0; i <= list.size()-1; i++) {
        int small = list.get(i);
        if (small > biggest) {
            biggest = small;
        }

    }
    System.out.println("The greatest number: " + biggest);
} else {
    // handle case - first number entered was -1
}
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43