问题
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 SwitCase {
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");
}
}
}
回答1:
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");
}
}
}
回答2:
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.
回答3:
Like that. Except char hi=hello;
should be char hi=hello.charAt(0)
. (Don't forget your break;
statements).
回答4:
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 '
回答5:
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);
}
}
来源:https://stackoverflow.com/questions/6906001/how-do-i-used-a-char-as-the-case-in-a-switch-case