i wrote a code for calculator and i use char variable to get the mathematicle operator ( , -, *, /) and i need to check what is the operator user input so i want to use if to check but cant use traditional way to check char what should i do
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 (" ")) {
}
}
}
CodePudding user response:
Since String is not one of the primitive types, that's why you compare it with equals()
for thevindu
you could just do thevindu == ' '
CodePudding user response:
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.