Search code examples
javacharjava.util.scannercharat

How the scannner input for character ( Operators ) work?


I wrote a code about result for operator input taken by user and please explain me how this character input work because when i was using

char operation = s.nextLine().charAt(0);

instead of

char operation = s.next().charAt(0);

Eclipse showed Error.

Code -

    System.out.println("Enter First Number:");
    int a = s.nextInt();

    System.out.println("Enter Second Number:");
    int b = s.nextInt();

    System.out.println("Which Operation you want to execute?");
    s.hasNextLine();
    char operation = s.next().charAt(0);    

    int result = 0;

    switch (operation) {
    case '+' :
        result = a + b;
        break;
    case '-' :
        result = a - b;
        break;
    case '*' :
        result = a * b; 
        break;
    case '/' :
        result = a / b;
        break;
    case '%' :
        result = a % b;
        break;
    default:
        System.out.println("Invalid Operator!");
    }
    System.out.println(result);
    s.close();
}

}


Solution

  • The problem is not because of s.nextLine(); rather, it is because of s.nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.

    Use

    int a = Integer.parseInt(s.nextLine());
    

    instead of

    int a = s.nextInt();
    

    I would recommend you create a utility function e.g. getInteger as created in this answer to deal with exceptional scenarios as well.