0

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

Nayuki
  • 17,911
  • 6
  • 53
  • 80
NaC114
  • 83
  • 8
  • 2
    Are you emptying the buffer after taking `x` and `y`? If not, the `nextLine()` will do that for you, and an empty line will be assigned to `opStr`, so `charAt(0)` will fire an exception. – BackSlash Sep 29 '13 at 12:13
  • See: http://stackoverflow.com/questions/18163518/while-loop-executes-only-once/18163608#18163608 – Nayuki Sep 29 '13 at 12:14
  • Also, start with: `String result = "Answer = " + x + "" + op + "" + y + "=" + answer; System.out.println(result);` – BlackBox Sep 29 '13 at 12:15

3 Answers3

8

nextDouble() doesn't handle the end of the line. So when you call nextLine() again, it'll take as input the enter (\n) you entered before. So it's skipping the actual input and swallows the \n from the previous input that was missed by nextLine(). You should call another nextLine() before the real nextLine() (So it will swallow the \n).

If you don't want to do that, you should construct another Scanner rather than using the same object.

That's the reason of your StringIndexOutOfBoundsException, opStr is only a \n at this point.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

The problem is that, after reading the double, the scanner input is not empty. Thus, the invocation of nextLine() returns immediately, returning the part of the last input that was not parseable as a floating-point value (which may be empty). If you invoke sc.nextLine() before asking for the operation, the next call to sc.nextLine() reads the line containing your operation.

Abrixas2
  • 3,207
  • 1
  • 20
  • 22
0

I built the world's simplest calculator when i began learning java. This should work fine for you :

import java.util.Scanner;
public class CalculatorProgram {
Scanner scan = new Scanner(System.in);
int N1;
int N2;
int O = 0;
System.out.println("Enter the first number:");
N1 = scan.nextInt();
System.out.println("Enter the second number:");
N2 = scan.nextInt();
System.out.println("Press 1 for addition, 2 for subtraction, 3 for multiplication, 4 for       division
O=scan.nextInt();
switch (O){
case 1:
O=N1+N2;
System.out.println(O);
break;
case 2:
O=N1-N2;
System.out.println(O);
break;
case 3:
O=N1*N2;
System.out.println(O);
break;
case 4:
O=N1/N2;
System.out.println(O);
break;

default:
System.out.println("That is an invalid selection. Thank you for using this program.");
break;

} 
}

}

Youre welcome.