我是一个完全的初学者,正在做一些虚构的项目来自学Java。我的脚本的目标是允许输入到arraylist,直到提供给定的退出命令。sc.next()是我上一次尝试后剩下的,但我的Google Fu还没有让我找到如何为arraylist设置自定义退出命令的答案。
正在寻找完成此任务的想法。
int i = 0;
while (sc.Next()) {
System.out.println("Respond end when done. Please enter dinner option #" + (i + 1));
String answer = sc.nextLine();
Dinner.add(answer);
i++;
}
//Randomizing the arraylist to print output
Random r = new Random();
{
int randomitem = r.nextInt(Dinner.size());
String randomElement = Dinner.get(randomitem);
System.out.println("Random Element = " + randomElement);
}
输出示例为…
Respond end when done. Please enter dinner option #1
American
Respond end when done. Please enter dinner option #2
Chinese
Respond end when done. Please enter dinner option #3
Pizza
Respond end when done. Please enter dinner option #4
Thai
Respond end when done. Please enter dinner option #5
end
目标是输入";结束";则它将移动到将输出数组列表项中的1个的随机化器上。
您可以使用不同条件的while循环。伪代码示例:
Scanner scanner = //init;
String answer = scanner.nextLine();
while(!answer.equals("end")) {
//add to list
answer = //read next input;
}
//do randomizing stuff