我的程序是ArrayList存儲輸入的號碼,當用戶輸入號碼-1時,程序將停止結束打印所有輸入號碼的升序。我的程序運行,但讓號碼進入,它不會打印出數字。它似乎是如果聲明不起作用。如何在if語句中調用ArrayList以正常工作?存儲輸入號碼的arraylist
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class testArrayList {
public static void main(String[] args) {
Scanner inputs = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
System.out.println("Enter a number(-1 to end): ");
while(inputs.hasNextInt()) {
nums.add(inputs.nextInt());
}
// it looks like it runs until here.
for (Integer n : nums) {
if (n == -1) {
Collections.sort (nums);
System.out.println("Here is the list of numbers : ");
System.out.println(n);
}
}
}
}
您是否嘗試過通過代碼帶有[調試器](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-步驟我診斷的 - 問題)? – litelite
爲什麼不使用int作爲原始數據,而不是整數? – Razvan
因爲不能將'int'放入'ArrayList'中。 – csmckelvey