3 回答

TA貢獻(xiàn)1825條經(jīng)驗 獲得超4個贊
您的代碼周圍沒有主循環(huán)。以下所有 while 循環(huán)都應(yīng)該可以解決問題。
while(a!=0 && b!=0) { ... }
因此,如果您的輸入之一為零,則不會繼續(xù)循環(huán)并且例程結(jié)束。否則,您的其他三個循環(huán)之一將處理輸入,請求新輸入,然后由主循環(huán)重新開始。

TA貢獻(xiàn)1871條經(jīng)驗 獲得超13個贊
您可以為此使用一個do-while循環(huán),該循環(huán)將始終至少執(zhí)行一次,然后在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循環(huán)來檢查每個條件,而是可以使用簡單的ifandif else語句來檢查每個外部循環(huán)的值是否更大。

TA貢獻(xiàn)1848條經(jīng)驗 獲得超10個贊
除了編輯循環(huán)條件之外,您還可以使用語句來改變控制流來退出循環(huán)中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");
添加回答
舉報