Search code examples
javavariablescharoperation

How to comapre chars in Java


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 ("+")) {
        } 
    }
}

Solution

  • Since String is not one of the primitive types, that's why you compare it with equals() for thevindu you could just do thevindu == '+'