【问题标题】:I'm stuck I want a while loop that takes in integer input however is broken by the keyword "ABC" what am I doing wrong我被卡住了我想要一个接受整数输入的 while 循环但是被关键字“ABC”打破我做错了什么
【发布时间】:2022-11-14 13:21:30
【问题描述】:
// defined variables and scanner;
` Scanner sc = new Scanner(System.in);
String response = "";
int totalVehicles = 0;
int i = 0;
System.out.println("RIVER BRIDGE SURVEY");
do{
System.out.println("How many vehicles are waiting?");
response = sc.next();
// if(){}else (this is a remnant of a hopeful past)
int waitingVehicles = Integer.parseInt(response);
totalVehicles = totalVehicles + waitingVehicles;
i = i + 1;
}
while(response.equals("ABC") ); // This condition is the problematic bit i think
`
尝试重新定义变量,取消定义变量,到处都是一些 if 语句,但没有任何效果。
也没有错误消息,但循环只运行一次
【问题讨论】:
标签:
java
loops
while-loop
do-while
【解决方案1】:
你的 while 循环条件是相反的,你需要一个 not (!)
需要while(!response.equals("ABC"))
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("RIVER BRIDGE SURVEY");
Scanner sc = new Scanner(System.in);
String response = "";
int totalVehicles = 0; int i = 0;
do{
System.out.println("How many vehicles are waiting?");
response = sc.next();
// if(){}else (this is a remnant of a hopeful past)
try {
int waitingVehicles = Integer.parseInt(response);
totalVehicles = totalVehicles + waitingVehicles;
i = i + 1;
} catch (NumberFormatException ex) {
// error here
}
}
while(!response.equals("ABC") ); // Added in !
}
这将继续运行,直到用户输入ABC
我还在 try { } catch {} 块中添加了应用程序填充获取 NumberFormatException 并无论如何退出循环。