How do I use a char as the case in a switch-case?
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 char
s do not correspond one-to-one with code-points. See codePointAt
for a way to reliably get a single Unicode codepoints.
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");
}
}
}
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);
}
}