![](/img/trans.png)
[英]Why do I have to enter in the input twice before my method accepts the input?
[英]Why do I have to write twice to add an input in the Arraylist?
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
}
我試圖從用戶那里獲得一些輸入並將它們存儲到 arraylist 中。 問題是我必須將項目寫入兩次才能將項目添加到列表中。 我不知道為什么!
而不是do-while
循環僅使用while
while (true){
System.out.println("Enter a product");
String product = input.nextLine();
if (!product.equalsIgnoreCase("q"))
arrayList.add(product);
else
break;
}
每次編寫readLine()
時,都會讀取一行。 在這個循環中,
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
readLine()
出現了兩次,因此每次迭代都會讀取兩行。 第一行始終添加到列表中,並且不檢查q
,第二行永遠不會添加到列表中,並且始終檢查q
。
你應該只做一次nextLine
:
while (true) {
System.out.println("Enter a product");
String product = input.nextLine(); // only this one time!
if (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
} else {
break;
}
}
發生它是因為input.nextLine()
使 java 讀取輸入。 您應該閱讀該行,然后才執行以下操作:
Scanner input = new Scanner(System.in);
String product = input.nextLine();
System.out.println("Enter a product");
while (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
System.out.println("Enter a product");
product = input.nextLine();
}
您可以使用 input.next() 讀取字符串值一次,並設置一個 while 循環,並且僅當值不等於 q 時才將更多值讀取到您的列表中。 如果您已經閱讀了兩次,則在您的 do 部分中將一個值添加到列表中,並且您在 while 部分中再次讀取的值僅與 q 進行比較,因此要退出您的代碼,您將丟失一個值並添加另一個,並且必須一個接一個地給出兩個 q 值才能退出它。 此外,由於大多數其他用戶已經給出了 nextLine 而不是 next 的答案,您可能需要檢查 next 做什么以及 nextLine 做什么。 簡而言之,如果您輸入由分隔符(默認空格)分隔的產品名稱,那么在 next 中,每個由空格分隔的值都被視為一個產品。 同樣,如果您也輸入不同的行。 但是,使用 nextLine,每條線作為一個整體將被添加為一個新產品。 這取決於您可能希望如何根據您的要求實現這一目標。
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
String product = input.next();
while(!product.equalsIgnoreCase("q")) {
arrayList.add(product);
product = input.next();
}
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.