[英]Scanner with ArrayList
在這個程序中,我打算這樣寫:它應該只通過掃描儀從用戶那里獲取正數,如果它們是正數 - 它需要將它們添加到“列表”數組列表中。 出於某種原因,當用戶添加它時,它不會添加第一個數字,而只會添加第二個數字(並且在每個 while 循環中都像這樣運行)。
有人可以幫忙嗎? 謝謝! :-)
import java.util.ArrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class Second_EX_Advanced_2 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Please enter a positive number ... ");
Scanner INPUT = new Scanner(System.in);
while (INPUT.nextInt() > 0) {
list.add(INPUT.nextInt());
System.out.println(list);
}
INPUT.close();
}
}
*
你實際上是在輸入兩次
while (INPUT.nextInt() > 0) { //first time here
list.add(INPUT.nextInt()); //second time here
System.out.println(list);
}
將其更改為
int n;
while ((n=INPUT.nextInt()) > 0) { //first time here
list.add(n); //second time here
System.out.println(list);
}
現在它應該可以正常工作了;
錯誤在你的 while 循環中:
while (INPUT.nextInt() > 0) {
list.add(INPUT.nextInt());
System.out.println(list);
}
您正在掃描第一個整數並添加第二個,如上所述。
在這里,您可以使用工作代碼:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class Second_EX_Advanced_2 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Please enter a positive number ... ");
Scanner INPUT = new Scanner(System.in);
int num;
while ((num = INPUT.nextInt()) > 0) {
list.add(num);
System.out.println(list);
}
INPUT.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.