我剛開始的Java,並試圖編寫一個簡單的計算器:初學者嘗試編寫一個簡單的計算器
我試過如下:
double x, y; //inputs
Scanner sc = new Scanner(System.in);
System.out.println("x?");
x = sc.nextDouble();
System.out.println("y?");
y = sc.nextDouble();
double answer = 0;
System.out.println("Operation type: (+,-,*,/)");
String opStr= sc.nextLine();
char op = opStr.charAt(0);
switch(op)
{
case '+':
answer=x+y;
break;
case '-':
answer=x-y;
break;
case '*':
answer=x*y;
break;
case '/':
if (y==0)
{
System.out.println("Error, can't divide by zero");
}
else
{
answer=x/y;
}
break;
default: System.out.println("Unkown operation");
} // switch end
System.out.println("answer = " +x+op+y+"=" + answer);
當我嘗試運行它,我得到以下幾點: (我可以輸入x和y,但後來我得到的錯誤信息。
Operation type: (+,-,*,/)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at edf_1.EDF_1.main(EDF_1.java:170)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
會很感激,如果有人能幫助我發現其中的錯誤或問題!
感謝
NAC
您是否在使用'x'和'y'後清空緩衝區?如果不是,'nextLine()'會爲你做這件事,而一條空行將被分配給'opStr',所以'charAt(0)'會觸發一個異常。 – BackSlash
另請參閱:http://stackoverflow.com/questions/18163518/while-loop-executes-only-once/18163608#18163608 – Nayuki
另外,從#開始:String result =「Answer =」+ x +「」+ op + 「」+ y +「=」+ answer; System.out.println(result);' – BlackBox