3 回答

TA貢獻1803條經驗 獲得超3個贊
您可以通過將所有內容移至循環(huán)中來極大地簡化您的代碼。然后,您可以將if條件breaks 置于循環(huán) if n1is之外0,并將 s 更改loop為無限循環(huán) untilbreak被調用。
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("Enter two numbers (0 to quit):");
float n1=sc.nextFloat();
if (n1 == 0){
break; //New part of the code
}
float n2=sc.nextFloat();
float ans1=n1+n2;
float ans2=n1*n2;
float ans3=ans1 / ans2;
System.out.println("Answer is "+ans3);
}
這種方式0永遠不會用于計算,也infinity永遠不會打印,因為您不會除以0.
示例運行:
Enter two numbers (0 to quit):
1 4
Answer is 1.25
Enter two numbers (0 to quit):
2 3
Answer is 0.8333333
Enter two numbers (0 to quit):
0

TA貢獻1813條經驗 獲得超2個贊
雖然這是一個非常簡單的問題,我希望您能夠自己解決,但在這里我嘗試向您解釋這個問題并提出解決方案:
您希望重復輸入直到輸入 0。while如您所見,您已經知道循環(huán)的概念。您現(xiàn)在可以使用它重復整個輸入和計算,直到用戶輸入 0:
Scanner sc =new Scanner(System.in);
float n1 = 1;
while(n1 != 0){
System.out.println("Enter two numbers:");
[...]
}
從上到下逐行瀏覽您的程序以了解您在做什么: 1. 創(chuàng)建一個掃描儀, 2. 定義 n1 = 1, 3. 只要 n1 != 0 ... 重復以下部分
然后,正如您提到的,您希望您的可執(zhí)行文件在 n1 = 0 時立即終止,而不僅僅是在循環(huán)代碼的末尾while。為此,您可以使用條件break:它直接跳轉到循環(huán)的末尾,在您的情況下,就是代碼的末尾。
我還想讓您知道continue直接進入循環(huán)的下一次迭代的命令。例如,如果有人輸入無效數(shù)據(jù),這將很有幫助。
你可以使用它如下:
Scanner sc=new Scanner(System.in);
float n1 = 1;
while(n1 != 0){ //loop until n1 == 0
System.out.println("Enter two numbers:");
n1=sc.nextFloat();
if(n1 == 0){ //if n1 equals 0
break; // goes to the end of the loop
}
float n2=sc.nextFloat();
if(n2 == 0){ //division by zero
System.out.println("Division by zero, try again!");
continue; //goes to the beginning of the loop again
}
float ans1=0;
float ans2=0;
float ans3=0;
int count=0;
ans1=n1+n2;
ans2=n1*n2;
count++;
ans3=ans1/ans2;
System.out.println("Answer is "+ans3);
}

TA貢獻1942條經驗 獲得超3個贊
您需要在 while 循環(huán)條件內進行輸入。這是因為除非用戶將他們的第一個數(shù)字輸入為零,否則您的循環(huán)將永遠運行。您還應該對 n2 進行某種錯誤檢查,因為它也不能為零。如果 n2 為零,則 ans2 為零。然后 ans3 將拋出一個被零除的錯誤。sc,nextFloat()還應注意,由于使用 a而不是,您在原始代碼中聲明 n2 時出錯sc.nextFloat()
這是一些代碼來演示我認為您要完成的工作。
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter two numbers:");
float n1=sc.nextFloat();
float n2=1;
float ans1=0;
float ans2=0;
float ans3=0;
int count=0;
while(n1!=0)
{
n2=sc.nextFloat();
while(n2 == 0)
{
System.out.println("Second number can not be zero. Enter a new number");
n2=sc.nextFloat();
}//End while loop for n2==0
ans1=n1+n2;
ans2=n1*n2;
count++;
ans3=ans1/ans2;
System.out.println("Answer is "+ans3);
System.out.println("Enter two numbers:");
n1=sc.nextFloat();
}//End while loop for n1
}//End main
我個人不喜歡使用 break 語句,因為我相信它會抑制循環(huán)條件的不良做法/不良設計。對于大多數(shù)情況,您應該能夠設置一個循環(huán)條件以在不進行不必要的迭代的情況下中斷。然而,這僅僅是意見,我的意見與我的教授告訴我的相符。
添加回答
舉報