1

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

}

Dhruv
  • 23
  • 8

2 Answers2

0

From the documentation of Scanner https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

So if you put .nextLine() you're in fact reading what has left since the last input to the next line (ie nothing). This can be demonstrated with this code

Scanner s = new Scanner(System.in);
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();
String s1 = s.nextLine();
String s2 = s.nextLine();
System.out.println(s1);
System.out.println(s2);
//char operation = s1.charAt(0); -> error
char operation = s2.charAt(0);//operator is read

The first print (s1) will not print anything. The second will print the operator.

fabiofili2pi
  • 887
  • 17
  • 34
0

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.

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72