P
P
PRAIT2019-07-25 17:52:48
Java
PRAIT, 2019-07-25 17:52:48

Error in declaring char variable?

Hello guys, please tell me how can I correctly declare a char variable so that the calculator would work.
Here I have the code:

import java.util.Scanner;

public class SimpleCalculator {

  public static void main(String[] args) {
    try (Scanner dev = new Scanner(System.in)) {
      int a, b;
      System.out.println("Please enter number A");
      a = dev.nextInt();
      System.out.println("Please enter number B");
      b = dev.nextInt();
      System.out.println("Please enter {+, -, *, /}");
      char ch = new Scanner(System.in).nextLine().charAt(0); // char - вот эта строка
      if (ch == '+') {
        System.out.println("a + b = " + (a + b));
      } else if (ch == '-') {
        System.out.println("a - b = " + (a - b));
      } else if (ch == '*') {
        System.out.println("a * b = " + (a * b));
      } else if (ch == '/') {
        System.out.println("a / b = " + (a / b));
      } else {
        System.out.println(" " + ch);
      }
    }
  }
}

With this execution, the code works correctly, but I want to declare ch immediately after int, and in this case, for some reason, the code stops working. Please tell me what am I doing wrong?
import java.util.Scanner;

public class SimpleCalculator {

  public static void main(String[] args) {
    try (Scanner dev = new Scanner(System.in)) {
      int a, b;
      char ch;
      System.out.println("Please enter number A");
      a = dev.nextInt();
      System.out.println("Please enter number B");
      b = dev.nextInt();
      System.out.println("Please enter {+, -, *, /}");
      ch = dev.nextLine().charAt(0); // char - вот эта строка!!!
      if (ch == '+') {
        System.out.println("a + b = " + (a + b));
      } else if (ch == '-') {
        System.out.println("a - b = " + (a - b));
      } else if (ch == '*') {
        System.out.println("a * b = " + (a * b));
      } else if (ch == '/') {
        System.out.println("a / b = " + (a / b));
      } else {
        System.out.println(" " + ch);
      }
    }
  }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-07-25
@PRAIT

The line of code b = dev.nextInt()reads a number from the input, but not the newline character following it. Therefore, called next dev.nextLine()will return an empty string that does not have a character at index 0. It is treated with a blunt but effective crutch - adding an additional line reading:

dev.nextLine();
ch = dev.nextLine().charAt(0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question