0

When I execute my code my program is terminated without scanning the string.

double x, y;
    String s;
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter Number: ");
    x = scan.nextDouble();
    System.out.println("Enter Number 2: ");
    y = scan.nextDouble();
    System.out.println("Enter Operater: x,+,/,-");
    s = scan.nextLine();
    if(s.equals("x"))
    {
        System.out.print(x * y);

    }
    else if(s.equals("+"))
    {
        System.out.print(x + y);

    }
    else if(s.equals("/"))
    {
        System.out.print(x / y);

    }
    else if(s.equals("-"))
    {
        System.out.print(x - y);

    }
    scan.close();

my program ends before s = scan.nextline(); How come it ends before?

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
Dark Dusk
  • 3
  • 2

2 Answers2

1

End of line you leave in the buffer. next( ) reads a token from the buffer until the next white space, while nextLine( ) reads up to \n

...
System.out.print("Enter Number 2: ");
y = scan.nextDouble();
System.out.print("Enter Operater: x,+,/,-");
s = scan.next();
...

Enter Number: 1
Enter Number 2: 2
Enter Operater: x,+,/,--
-1.0
0

The user input, optimally, would look like this:

-CURSOR HERE- num1 NEWLINE

num2 NEWLINE

operator NEWLINE

If you do several nextDouble() calls, the program will read one double first.

num1 -CURSOR HERE- NEWLINE

num2 NEWLINE

operator NEWLINE

Then, the user must type an enter to submit the input, so the second nextDouble() can't find anything to read, since there is no number directly after the cursor. It needs a nextLine() to absorb the newline.

Unfortunately, you have a nextLine() in the wrong place, which absorbs the newline.

num1 NEWLINE

-CURSOR HERE- num2 NEWLINE

operator NEWLINE

So, your program absorbs the double in the first nextDouble(), nothing in the second, and the newline in nextLine().

To fix this, put a scan.nextLine() right after each nextDouble(). You don't have to read the nextLine() calls into anything, other than the one that has the operator.

Community
  • 1
  • 1
ameed
  • 1,107
  • 6
  • 23