Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
        }
    }   
}
like image 848
Zhianc Avatar asked Aug 02 '11 00:08

Zhianc


People also ask

Can I use char in switch-case?

You can use char 's for the switch expression and cases as well.

Can we use char in switch-case in Java?

The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch.

Can we use char in switch-case in CPP?

switch statement can handle int and char in C++. char data type can hold only one letter.

Can a string be used in a case statement inside a switch?

Yes, we can use a switch statement with Strings in Java.


3 Answers

Here's an example:

public class Main {

    public static void main(String[] args) {

        double val1 = 100;
        double val2 = 10;
        char operation = 'd';
        double result = 0;

        switch (operation) {

            case 'a':
                result = val1 + val2; break;

            case 's':
                result = val1 - val2; break;
            case 'd':
                if (val2 != 0)
                    result = val1 / val2; break;
            case 'm':
                result = val1 * val2; break;

            default: System.out.println("Not a defined operation");


        }

        System.out.println(result);
    }
}
like image 184
Revanth Avatar answered Nov 08 '22 22:11

Revanth


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");
        }
    }   
}
like image 37
Pablo Fernandez Avatar answered Nov 08 '22 21:11

Pablo Fernandez


charAt gets a character from a string, and you can switch on them since char is an integer type.

So to switch on the first char in the String hello,

switch (hello.charAt(0)) {
  case 'a': ... break;
}

You should be aware though that Java chars do not correspond one-to-one with code-points. See codePointAt for a way to reliably get a single Unicode codepoints.

like image 37
Mike Samuel Avatar answered Nov 08 '22 23:11

Mike Samuel