我有這段代碼應該通過掃描器的next()或nextLine()方法將字符串值添加到arrayList。 next()的問題在於它忽略了第一個空格之後的所有內容,所以我應該使用nextLine()方法。 nextLine()的問題在於它沒有記錄輸入,而是在arrayList中存儲了一些空格。下面的代碼:Java:nextLine()跳過輸入並向arrayList添加空格
System.out.println("\nWhat is your idea? ");
String i = in.nextLine();
in.nextLine();
meals.add(i);
System.out.println("\n" + i + " has been entered into the idea pool. \n");
System.in.read();
我添加了額外的「in.nextLine()」的首字母后「字符串I = in.nextLine()」,因爲這是我發現,當我研究這個問題,但沒有關係的唯一的解決方法它不適合我,它只是存儲了一些空白空間。而且,System.in.read();
在結尾處僅存在,以便它在輸入後不會向前跳躍。
這裏就是上述樣品裝配到代碼:
ArrayList<String> meals = new ArrayList<String>();
String select = "";
while(!select.equals("")){
System.out.println("What would you like to do?");
System.out.println("1. <Irrelevant>");
System.out.println("2. Enter an idea");
System.out.println("3. <Irrelevant>");
System.out.println("4. <Irrelevant>");
System.out.println("Q. <Irrelevant>");
select = in.next();
switch(select){
case "1":
//Some stuff here.
case "2":
//Here's where the above problem fits into.
case "3":
//More stuff here
//and so on...
}
}
爲什麼使用'System.in.read();'?沒有意義。 –