Reputation: 69
I wrote a code for calculator and I use char
variable to get the mathematical operator (+, -, *, /)
. I need to check what operator did user input, but for some reason this code is not working. How can I compare char
in Java?
import java.util.Scanner;
public class test_2 {
public static void main(String args[]) throws InterruptedException {
double val1, val2, total;
char thevindu;
Scanner input = new Scanner (System.in);
System.out.println("enter frist number");
val1 = input.nextDouble();
System.out.println("type operation");
thevindu = input.next().charAt(0);
System.out.println("enter second number");
val2 = input.nextDouble();
if (thevindu.equals ("+")) {
}
}
}
Upvotes: 0
Views: 171
Reputation: 114
As others have said, chars can be directly compared using ==. This is because to a computer, a char is simply a number; only you defining what it should be interpreted as (when you declare the variable) sets apart a lowercase 'a' from the int 97. So even if in natural language asking if a variable is "equal" to the letter 'a' is strange, to a computer it makes perfect sense.
Strings cannot be compared in this way because they are non-primitive; they're actually an array of characters, and can't be directly compared.
Upvotes: 1
Reputation: 151
Since String is not one of the primitive types, that's why you compare it with equals()
for thevindu
you could just do thevindu == '+'
Upvotes: 3