Skip to content
Advertisement

How do I use a char as the case in a switch-case?

How do I use a character in a switch-case? I will be getting the first letter of whatever the user inputs.

import javax.swing.*;

public class SwitchCase {
    public static void main (String[] args) {
        String hello = "";
        hello = JOptionPane.showInputDialog("Input a letter: ");
        char hi = hello;
        switch(hi) {
            case 'a': System.out.println("a");
        }
    }   
}

Advertisement

Answer

public class SwitCase {
    public static void main(String[] args) {
        String hello = JOptionPane.showInputDialog("Input a letter: ");
        char hi = hello.charAt(0); // get the first char.
        switch(hi) {
            case 'a': System.out.println("a");
        }
    }   
}
Advertisement