[英]Java reading multiple variable from a single line, but how to terminate using one variable?
Scanner br = new Scanner(System.in);
int a = br.nextInt();
int b = br.nextInt();
int c = br.nextInt();
If I only want to enter a single value, for example "0" to terminate the program, how do I do that?如果我只想输入一个值,例如“0”来终止程序,我该怎么做? Because with the code above you have to enter 3 values, right?
因为上面的代码你必须输入 3 个值,对吗?
Try using a while loop, and a list to store the data.尝试使用 while 循环和一个列表来存储数据。
boolean mustContinue = true;
List<Integer> result = new ArrayList<Integer>();
while(mustContinue) {
Integer a = br.nextInt();
if(a == 0) {
mustContinue = false;
} else {
result.add(a);
}
}
This is not a complete running code, it's just to give you an idea of a possible solution.这不是完整的运行代码,只是为了让您了解可能的解决方案。 There are some thing to care of in order to make it a complete running code (for example check
br.hasNextInt()
to prevent exception, etc).为了使它成为一个完整的运行代码,有一些事情需要注意(例如检查
br.hasNextInt()
以防止异常等)。
You can do it by using a while loop, it will end when you type 0:您可以使用 while 循环来完成,当您输入 0 时它会结束:
Scanner sc = new Scanner(System.in);
int num;
while (sc.hasNextInt() && ((num = sc.nextInt()) != 0))
{
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.