I just started Java and was trying to program a simple calculator:
I tried the following:
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);
When I try to run it I get the following: (I can input x and y, but afterwards I get the error message.
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)
Would be really grateful if anyone can help me find the mistake or issue!
Thanks
NaC