0

In the following code, after going through "Enter first number", the program outputs both print statements afterwards at the same time. This happens when I use the nextLine method, but when I use just scanner.next(), it seems to work fine. Why does this happen?

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        String operator = scanner.nextLine();

        System.out.print("Enter second number: ");
        double num2 = scanner.nextDouble();

        if (operator.equals("+")){
            System.out.println("Result: " + (num1 + num2));
        }


    }
}
Ichigo Kurosaki
  • 3,555
  • 8
  • 35
  • 51
Lucas
  • 105
  • 4
  • 1
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – maloomeister Jan 18 '21 at 11:52
  • Yes, thank you. – Lucas Jan 18 '21 at 12:00

0 Answers0