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");
}
}
}
You can use char 's for the switch expression and cases as well.
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.
switch statement can handle int and char in C++. char data type can hold only one letter.
Yes, we can use a switch statement with Strings in Java.
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);
}
}
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");
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With