【发布时间】:2020-09-19 22:51:52
【问题描述】:
我是 * 的新手,想知道为什么当我在我的 while 循环中引入 if 语句@“如果完成,请键入“返回””时,我的语句会不断重复两次。其次,有人能告诉我为什么当我只向 ArrayList 添加一项时,ArrayList 在索引 0 处保留一个空字符串吗?谢谢!
代码如下:
包 com.codewithrichard;
导入 java.util.ArrayList; 导入 java.util.Scanner;
公共类主{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//global variables
boolean appIsStillOn = true;
ArrayList <String> shoppingList = new ArrayList<>();
System.out.println("Welcome to your mobile shopping list" + "\n" + "Your options are");
System.out.println("1) add item to list");
System.out.println("2) display list and amount of items in it");
System.out.println("3) quit!");
while (appIsStillOn) {
System.out.println("Option (1-4): ");
int option1 = input.nextInt();
if (option1 == 1) {
while (true) {
System.out.println("item (if done, type \"back\"): ");
String itemAdded = input.nextLine().toLowerCase();
if (!itemAdded.equals("back")) {
shoppingList.add(itemAdded);
} else {
break;
}
}
}
else if (option1 ==2){
System.out.println(shoppingList);
System.out.println("size of shopping list: " + shoppingList.size());
}
else {
System.out.println("Can't wait for you to come back!");
appIsStillOn = false;
}
}
}
}
【问题讨论】:
-
你试过调试吗?调试器中有什么不清楚的地方?
-
第一次调用
input.nextLine()时,Scanner会占用您在int菜单选项中键入的行的其余部分。第一次调用将返回一个空字符串,该字符串将成为列表中的第一项。
标签: java if-statement arraylist while-loop