[英]Java: ArrayLists w/ Scanner: First element not printing
我試圖制作一個在ArrayList
中打印出用戶輸入的值的程序,並且在大多數情況下都可以工作。 除非它不打印第一個元素。 這是代碼:
import java.util.Scanner;
import java.util.ArrayList;
public class Family {
public static void main(String[] args){
ArrayList<String> names=new ArrayList<String>();
Scanner in=new Scanner(System.in);
System.out.println("Enter the names of your immediate family members and enter \"done\" when you are finished.");
String x=in.nextLine();
while(!(x.equalsIgnoreCase("done"))){
x = in.nextLine();
names.add(x);
}
int location = names.indexOf("done");
names.remove(location);
System.out.println(names);
}
}
例如,如果我輸入jack,bob和sally,它將顯示[bob,sally]
當您進入循環時,您將立即調用nextLine()
,從而在該過程中丟失先前輸入的行。 在讀取其他值之前,應使用它:
while (!(x.equalsIgnoreCase("done"))) {
names.add(x);
x = in.nextLine();
}
編輯:
當然,這意味着不會將"done"
添加到names
,因此以下各行以及它們應被刪除:
int location = names.indexOf("done");
names.remove(location);
String x=in.nextLine();
while loop
外的這一行消耗了第一個輸入,因為當您進入while loop
,您再次調用x=in.nextLine();
而不保存第一個輸入,因此會丟失。 因此它不會被打印,因為它不在ArrayList
。
只需刪除String x=in.nextLine();
在while loop
之前包含該代碼,您的代碼將正常運行。
String x="";
System.out.println("Enter the names of your immediate family members and enter \"done\" " +
"when you are finished.");
while(!(x.equalsIgnoreCase("done"))){
x = in.nextLine();
names.add(x);
}
因為第一個元素被第一個x= in.nextLine();
而且您從未將其添加到列表中。
嘗試這個:
System.out.println("Enter the names of your immediate family members and enter \"done\" when you are finished.");
String x="";
while(!(x.equalsIgnoreCase("done"))){
x = in.nextLine();
names.add(x);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.