Skip to content
Advertisement

Is there a way to use or operator || on char in java?

Im new in programming, so this is kind of basic but I cant find an answer here on why is this keep happenning. “The operator || is undefined for the argument type(s) char, char”,can someone please help, its for our task. Thanks in advance.

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        char choice = (scan.next().charAt(0));
        switch (choice) {
        case ('A'||'a'):
            System.out.println("Wrong Answer");
            break;
        
        }
        
    }

}

Advertisement

Answer

You can’t logically OR together characters in Java. The closest thing to what you want to do in Java might be:

switch (choice) {
    case 'A':
    case 'a':
        System.out.println("Wrong Answer");
    break;
}

Here we are letting both cases of A to flow to the same case. Another option:

switch (Character.toUpperCase(choice)) {
    case 'A':
        System.out.println("Wrong Answer");
    break;
}

This approach first uppercases the input character, and then we only need to check uppercase letters in the switch statement.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement