0

I'm trying to make a calculator program that loops, where the user can enter a number, then the operation he whish to perform on this number until he enters "=" as an operator. The variable containing the result is initialized as zero in the class and the default operator applied is "+".

import java.util.Scanner;

public class main {

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

        Calculator c = new Calculator();
        boolean flow = true;

        while(flow) {
            System.out.println("Number :");
            int userEntry = scan.nextInt();
            System.out.println("Operator :");
            String operation = scan.nextLine();

            switch(operation) {
            case "+":
                c.setOperation(Calculator.ADDITION);
                break;
            case "-":
                c.setOperation(Calculator.SOUSTRACTION);
                break;
            case "*":
                c.setOperation(Calculator.MULTIPLICATION);
                break;
            case "=":
                c.getResult();
                return;
            default:
                System.out.println("Please enter a valid operator.");
            }
            c.apply(userEntry);
            c.getResult();
        }
    }
}

But everytime I try to run the program, I get this result

Number :
4
Operator :
Please enter a valid operator.
Number :
67
Operator :
Please enter a valid operator.
Number :

The program doesn't let me put an input in the operator and directly skip to the next the next int input. I've been trying various way to write this, like taking that part out of the loop but its still the same error and i can't see what's causing this. Any help would be really appreciated.

Mistogrif
  • 3
  • 3

1 Answers1

0
/** Scanning problems */
class Scanning {
    public static void main(String[] args) {
        int num;
        String txt;
        Scanner scanner = new Scanner(System.in);

        // Problem: nextLine() will read previous nextInt()
        num = scanner.nextInt();
        txt = scanner.nextLine();

        // solution #1: read full line and convert it to integer
        num = Integer.parseInt(scanner.nextLine());
        txt = scanner.nextLine();

        // solution #2: consume newline left-over
        num = scanner.nextInt();
        scanner.nextLine();
        txt = scanner.nextLine();
    }
}
Khaled Eid
  • 22
  • 5