如何在交换机案例中使用char作为案例?

如何在开关盒中使用字符? 我将收到用户输入的第一个字母。

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"); } } } 

 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是一个整数类型。

所以要打开String hello的第一个char

 switch (hello.charAt(0)) { case 'a': ... break; } 

您应该知道Java char与代码点一对一不对应。 有关可靠地获取单个Unicode代码点的方法,请参阅codePointAt

像那样。 char hi=hello;除外char hi=hello; 应该是char hi=hello.charAt(0) 。 (不要忘记你的break;陈述)。

当变量是字符串时使用char将不起作用。 运用

 switch (hello.charAt(0)) 

您将提取hello变量的第一个字符,而不是尝试以字符串forms使用该变量。 你还需要摆脱你的空间

 case 'a ' 

这是一个例子:

 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); } }