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));
}
}
}