2 回答

TA貢獻1772條經(jīng)驗 獲得超8個贊
問題是你沒有跳出內(nèi)循環(huán)。在這里我將如何編寫相同的代碼:
import java.util.ArrayList;
import java.util.Scanner;
public class ReadNumbers {
public static void main(String[] args) {
ArrayList<Integer> inputs = new ArrayList<Integer>();
System.out.println("Enter some numbers: ");
try (Scanner scnr = new Scanner(System.in)) {
do {
inputs.add(scnr.nextInt());
System.out.println("Would you like to enter another y/n?");
} while (scnr.next().equalsIgnoreCase("y"));
}
System.out.println(inputs);
}
}
這會產(chǎn)生以下輸出:
Enter some numbers:
14
Would you like to enter another y/n?
y
15
Would you like to enter another y/n?
y
17
Would you like to enter another y/n?
y
44
Would you like to enter another y/n?
n
[14, 15, 17, 44]
讀取數(shù)字的另一種方法是從空格分隔的行中讀取幾個:

TA貢獻1852條經(jīng)驗 獲得超7個贊
我認為你把這個復雜化了。您只需要一個循環(huán),該循環(huán)一直運行到用戶輸入“n”為止。
在此之前,要求用戶輸入一個數(shù)字,讀入,然后詢問他們是否要繼續(xù)。適當?shù)馗卵h(huán)條件,你就完成了:
public static void main(String... args) {
ArrayList<Integer> inputs = new ArrayList<Integer>();
try (Scanner scnr = new Scanner(System.in)) {
boolean valid = true;
while (valid) {
System.out.println("Enter some numbers: ");
if (scnr.hasNextInt()) {
inputs.add(scnr.nextInt());
}
System.out.println("Would you like to enter another?");
String response = scnr.next();
valid = response.trim().equalsIgnoreCase("y");
}
}
System.out.println(inputs);
}
產(chǎn)生輸出
Enter some numbers:
1
Would you like to enter another?
y
Enter some numbers:
2
Would you like to enter another?
y
Enter some numbers:
3
Would you like to enter another?
n
[1, 2, 3]
添加回答
舉報