I'm making a simple calculator, but I've run into a problem where a string input is skipped. Here is my code:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Calculator\n");
while (true) {
System.out.print("Number: ");
float num1 = input.nextFloat();
System.out.print("Operator: ");
String optr = input.nextLine();
System.out.print("Number: ");
float num2 = input.nextFloat();
System.out.println(num1 + num2);
}
}
}
I have tried doing \n but I don't know what else I should really do as I don't know what the problem is.
I know input is never closed, but I have tried closing it. It has no affect and I don't want to add it right now as I am making the base system.
1 Answer
Instead of using...
System.out.print("Operator: ");
String optr = input.nextLine();
...use this...
System.out.print("Operator: ");
String optr = input.next();
The method nextLine() is a bit finnicky. Long story short, if you use nextLine(), beware that it doesn't play well with next(), nextInt(), nextFloat(), etc.
If you want the long story, here is a more detailed explanation --