這個賦值是讀取ArrayList的最大值並返回它,如果它是0或者空則返回並打印null。但是,當我運行它,輸出爲null爲負數時,它應該只返回空值0爲什麼這個返回null?
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;
}
}
樣品試驗
-12
-151
-1221
-2121
-61
-42
0
null
你是否檢查元素是否被添加到列表中? – Kakarot