Answer the question
In order to leave comments, you need to log in
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);
}
}
}
}
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
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 questionAsk a Question
731 491 924 answers to any question