我刚开始使用 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)
如果有人能帮助我找到错误或问题,将不胜感激!
谢谢
氯化钠