3 回答
TA贡献1825条经验 获得超4个赞
您的代码周围没有主循环。以下所有 while 循环都应该可以解决问题。
while(a!=0 && b!=0) { ... }
因此,如果您的输入之一为零,则不会继续循环并且例程结束。否则,您的其他三个循环之一将处理输入,请求新输入,然后由主循环重新开始。
TA贡献1871条经验 获得超13个赞
您可以为此使用一个do-while循环,该循环将始终至少执行一次,然后在bora等于 0 时退出:
public static void main(String[] args){
@SuppressWarnings("resource") //Used to remove unclosed warning
Scanner input = new Scanner(System.in);
int a;
int b;
do {
System.out.println("Enter value for a: ");
a = input.nextInt();
System.out.println("Enter value for b: ");
b = input.nextInt();
if (a < b) {
System.out.println("a is less than b");
}
else if (a > b) {
System.out.println("a is greater than b");
}
else if (a == b) {
System.out.println("a is equal to b");
}
} while (a != 0 && b != 0);
System.out.println("Loop has finished!");
}
示例运行:
Enter value for a:
1
Enter value for b:
3
a is less than b
Enter value for a:
3
Enter value for b:
5
a is less than b
Enter value for a:
0
Enter value for b:
1
a is less than b
Loop has finished!
您不需要使用while循环来检查每个条件,而是可以使用简单的ifandif else语句来检查每个外部循环的值是否更大。
TA贡献1848条经验 获得超10个赞
除了编辑循环条件之外,您还可以使用语句来改变控制流来退出循环中break。这可以这样做:
int a;
int b;
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Enter a: ");
a = Integer.parseInt(input.nextLine());
System.out.println("Enter b: ");
b = Integer.parseInt(input.nextLine());
if(a == 0 || b == 0) break;
String comparison = (a > b) ? "is bigger than" : (a < b) ? "is less than" : "is equal to";
System.out.println("a "+comparison+" b");
}
String exitReason = (a == 0 && b == 0) ? "a and b are" : (a == 0) ? "a is" : "b is";
System.out.println("Exited because "+exitReason+" equal to zero");
添加回答
举报