user3525298
user3525298

Reputation: 19

Why is this returning null?

The assignment is to read the maximum value of the ArrayList and return it, and if it's 0 or empty return and print null. But when I run it, the output is null for negative numbers when it should only return null for 0.

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

    int addNum = -1;

    //User inputs numbers for the list until they input 0
    while (addNum != 0) {

        addNum = input.nextInt();
        list.add(addNum);

    }

    //Sends it to the method to check for the biggest number
    Integer i = max(list);

    //It returns null if it's negative for some reason
    if (i == null) {
        System.out.println((String) null);
    } else {
        System.out.println("The greatest number is " + i);
    }
}

public static Integer max(ArrayList<Integer> list) {
    Integer i = Collections.max(list);

    //Even though the if statement says only if it is equal to 0
    if (i == 0) {
        return (null);
    } else {
        return i;
    }
}

Sample Run

-12
-151
-1221
-2121
-61
-42
0
null    

Upvotes: 0

Views: 126

Answers (2)

Kakarot
Kakarot

Reputation: 4252

The error is because If user enters 0, it is added to the list and in the next iteration you break the while loop. You need to fix it.

Upvotes: 0

TTT
TTT

Reputation: 2012

Your problem is here :

//User inputs numbers for the list until they input 0
while (addNum != 0) {

    addNum = input.nextInt();
    list.add(addNum);

}

When you get the 0, you also add it to the list. Lexically, 0 is greater than all negative integers, so your max() function always returns null.

You can fix it like this(this is a hackjob, there are better ways, you probably want to consider how you're doing things, it's pretty redundant currently):

//User inputs numbers for the list until they input 0
while (addNum != 0) {

    addNum = input.nextInt();
    if(addNum == 0)
        break;
    list.add(addNum);

}

Upvotes: 5

Related Questions