如何在 switch-case 中使用字符?我将收到用户输入的任何第一个字母。
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");
}
}
}
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
从字符串中获取一个字符,并且您可以打开它们,因为char
是整数类型。
因此要打开
char
String
中的第一个 hello
,
switch (hello.charAt(0)) {
case 'a': ... break;
}
您应该意识到 Java
char
并不与代码点一一对应。请参阅 codePointAt
了解可靠获取单个 Unicode 代码点的方法。
这是一个例子:
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);
}
}
就像那样。除了
char hi=hello;
应该是 char hi=hello.charAt(0)
。 (不要忘记您的 break;
陈述)。
当变量是字符串时使用 char 是行不通的。使用
switch (hello.charAt(0))
您将提取 hello 变量的第一个字符,而不是尝试以字符串形式按原样使用该变量。你还需要清理掉里面的空间
case 'a '
如果您正在接受用户的输入,请尝试此操作:
Scanner sc = new Scanner(System.in);
char alphabet = sc.next().charAt(0);
switch(alphabet) {
case 'a': System.out.println("Apple");
break;
case 'b': System.out.println("Ball");
break;
default: System.out.println("Error");
}