【发布时间】:2020-07-19 04:13:37
【问题描述】:
我正在尝试为用户输入的每个输入运行 while 循环,但如果用户没有输入输入,我不知道如何停止。 如果用户没有输入输入,我需要帮助来停止 while 循环。
代码:
import java.util.*;
class petrol{
public static void main(String[] args){
int vehicle_counter=0,petrol_counter=0;
System.out.println("Enter quantity of petrol to be filled in vehicles seperated by space:");
Scanner s1 = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<Integer>();
while(true){
if(petrol_counter<=200 && array.size()<50){
int input = s1.nextInt();
petrol_counter=petrol_counter+input;
vehicle_counter++;
array.add(input);
}
else{
System.out.println("Quantity Excedded then 200 Litres or no of Vehicles excedded then 50.");
break;
}
}
System.out.println("Hii");
}
}
例如:如果我输入 2 3 4 2 并按 enter 循环应该停止。
可能解决的问题:
如果我使用 while(s1.nextInt().equals(true)) 我会收到错误消息。
如何使用break?
【问题讨论】:
-
正如 Maruthi 在回答部分中提到的那样,
BufferedReader是更好的方法。但是如果你仍然想坚持Scanner,那么这不是一个更可取的解决方案,只是为了给你另一个思路,也许你可以使用while(s1.hasNextInt())而不是while(true)。现在,如果您想停止输入值,那么在按 enter 之前输入任何非整数字符,例如标点符号。 -
@AniruddhaSardar
s1.hasNextInt()有效。我添加了一个 cooment 以在末尾添加句点(。)。
标签: java while-loop