【发布时间】:2019-11-06 21:25:29
【问题描述】:
我正在创建一个包含用户在控制台中输入的字符串的数组列表。问题是当他们输入超过 2 个单词的 String 时,程序无法按预期运行。
这是我目前所拥有的:
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner (System.in);
int i;
System.out.print("How many TV shows do you hope to watch this week? ");
i = scan.nextInt();
scan.nextLine();
for(int j = 0; j<i; j++){
System.out.print("Enter show " + (j+1) + ": ");
list.add(scan.nextLine());
}
System.out.print("Have you caught up to any shows (answer yes or no): ");
while (scan.nextLine().equalsIgnoreCase("yes")){
System.out.print("Which show? ");
String show = new String(scan.nextLine());
if(list.contains(show)){
list.remove(list.indexOf(show));
}else {
System.out.print("That show is not on original list!");
}
}
System.out.println("Here's what you still have to watch this week:");
System.out.println(list);
顺便说一句,我已经尝试从 next() 更改为 nextLine() 它仍然无法按预期工作。
我的预期输出如下:
示例 1:假设您没有赶上任何节目 (这工作,感谢用户的回应,在下面)
How many TV shows do you hope to watch this week? 3
Enter show 1: RWBY
Enter show 2: Kengan Ashura
Enter show 3: The Good Place
Have you caught up to any shows (answer yes or no): no
Here's what you still have to watch this week:
[RWBY, Kengan Ashura, The Good Place]
示例 2:假设您已经赶上了一个节目并将更新列表 (不工作)
How many TV shows do you hope to watch this week? 3
Enter show 1: Father Brown
Enter show 2: Death in Paradise
Enter show 3: Watchmen
Have you caught up to any shows (answer yes or no): yes
Which show? Death in Paradise
Any other shows you're caught up with? (yes/no) no
Here's what you still have to watch this week:
[Father Brown, Watchmen]
示例 3:假设您赶上了一个节目,但它不在列表中。 (它不会更新列表,因为将您赶上的新节目添加到列表中只是为了删除它是没有意义的。)
How many TV shows do you hope to watch this week? 2
Enter show 1: Watchmen
Enter show 2: RWBY
Have you caught up to any shows (answer yes or no): yes
Which show? Monday Night Football
That show is not on original list!
Any other shows you're caught up with? (yes/no) no
Here's what you still have to watch this week:
[Watchmen, RWBY]
谢谢!
【问题讨论】:
-
不,如果你测试我的代码,你会注意到如果你从 next() 更改为 nextLine() 它仍然不能按预期工作。
-
还有stackoverflow.com/questions/13102045/…,需要看nextInt()后面的返回行
-
这也没有帮助。 :(
-
@MarkSantos 你能发布你的实际输出吗?
-
我试过了,它有效,用这段代码检查你使用 scnanner 的方式与我在 cmets ideone.com/1XzEHz987654322@ 中指出的两个地方相同
标签: java string for-loop java.util.scanner