我是一個字符串來做一個簡單的計算器,如果一個人被零除以它不會破壞代碼。我真的沒有什麼理想,我做了什麼我可以做什麼。我需要得到這個不要school.my家庭作品讀取執行加,減,乘和除兩個numbers.handle無效異常和算術異常。卡在循環while while循環使用try
import java.util.*;
public class Calcultator {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int w1=0;
int w2=0;
int w3=0;
double i1 = 0;
double i2=0;
String sign1 = null;
double sum=0;
do {
try {
System.out.println("Enter a your first number");
i1=scan.nextDouble();
w1++;
System.out.println("il="+1l);
System.out.println("w1="+w1);
} catch(Exception e) {
System.out.println("you must enter a number");
w1=0;
}
} while(w1==0);
do {
try {
System.out.println("Enter a your first number");
i2=scan.nextDouble();
w1++;
} catch(Exception e) {
System.out.println("you must enter a number");
}
} while(w2==0);
do {
try {
System.out.println("1)/ 2)* 3)- 4)+");
int sign=scan.nextInt();
switch(sign) {
case 1:
if(i1==0 || i2==0){
System.out.println("Zero can not be Devided");
break;
} else {
sign1="/";
break;
}
case 2:
sign1="*";
break;
case 3:
sign1="-";
break;
case 4:
sign1="+";
break;
default :
break;
}
} catch(Exception e) {
System.out.println("you must enter a number");
}
} while(w3==0);
if(sign1=="/") {
sum=i1/i2;
System.out.println(i1 +"/"+i2+"="+sum);
} else if(sign1=="*") {
sum=i1*i2;
System.out.println(i1 +"*"+i2+"="+sum);
} else if(sign1=="-") {
sum=i1-i2;
System.out.println(i1 +"-"+i2+"="+sum);
} else {
sum=i1+i2;
System.out.println(i1 +"+"+i2+"="+sum);
}
scan.close();
}
}
可能的重複http://stackoverflow.com/questions/28623651/scanner-nextline-return-null/28623706#28623706 –
請使用一致的縮進來正確格式化您的代碼。目前很難閱讀。我懷疑你使用了空格和製表符的組合,這就是爲什麼它會被破壞。對於SO,如果您只使用空格縮進,則效果最佳,因此「標籤」的寬度沒有多大差別。 –
提示:你的catch語句是**不**有幫助。它只是告訴你「發生了同樣的錯誤」。將其更改爲告訴**發生了哪種錯誤,例如通過打印其消息和/或堆棧跟蹤。而代碼格式**很重要**。我還建議在**命名上花費更多時間,因爲你使用的名字不會告訴他們背後的事情。 – GhostCat