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");
}
}
}
This question is related to
java
switch-statement
character
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");
}
}
}
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 '
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.
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 that. Except char hi=hello;
should be char hi=hello.charAt(0)
. (Don't forget your break;
statements).
Source: Stackoverflow.com