Alex Rivera | Logout

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

Asked 2011-08-02T00:23:06.983
13

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");
        }
    }   
}
Edit
Report

2 Answers

23
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");
        }
    }   
}
answered 2011-08-02T00:26:37.717
0

Using a char when the variable is a string won't work. Using

switch (hello.charAt(0)) 

you will extract the first character of the hello variable instead of trying to use the variable as it is, in string form. You also need to get rid of your space inside

case 'a '
answered 2011-08-02T00:30:14.363

Your Answer