0

as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner inp = new Scanner(System.in);
    Methods operation = new Methods();
    boolean loop = false;




    do {

    System.out.println("Enter an operator symbol - +, -, * or /");
    String symb = inp.nextLine(); //this is the line which is skipped 


    System.out.println("Enter a number");
    int num1 = inp.nextInt();
    inp.nextLine();

    System.out.println("Enter a second number");
    int num2 = inp.nextInt();
    inp.nextLine();

    switch(symb) {
    case "+" : 

    operation.setA(num1);
    operation.setB(num2);
    int totalAddition = operation.addNums(num1,num2);
    System.out.println("The result is - " + totalAddition);
    break;

    case "-" : 
    operation.setA(num1);
    operation.setB(num2);
    int totalSubtract = operation.subtractNums(num1,num2);
    System.out.println("The result is - " + totalSubtract);
    break;

    case "*" : 
        operation.setA(num1);
        operation.setB(num2);
        int totalMult = operation.multNums(num1,num2);
        System.out.println("The result is - " + totalMult);
        break;

    case "/" : 
        operation.setA(num1);
        operation.setB(num2);
        int totalDiv = operation.divNums(num1,num2);
        System.out.println("The result is - " + totalDiv);
        break;
    }
    System.out.println("Would you like to exit? Y/N");
    char ans = inp.next().charAt(0);

    if(ans == 'Y' || ans == 'y') {
        loop = true;
        inp.close();
        System.exit(0);
    }
    else { 
        loop = false;
    }
    }
    while(loop == false);
    }
}
Andre Mousu
  • 37
  • 1
  • 6
  • Change `char ans = inp.next().charAt(0);` to `char ans = inp.nextLine().charAt(0);` - otherwise you leave a trailing end-of-line. – Elliott Frisch Jun 10 '18 at 14:53
  • Many thanks Mr Frisch! – Andre Mousu Jun 10 '18 at 15:09
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – QBrute Jun 10 '18 at 15:31

0 Answers0