如何在开关盒中使用char作为案例?

时间:2011-08-02 00:23:07

标签: java character

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

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

5 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:7)

charAt从字符串中获取一个字符,您可以打开它们,因为char是整数类型。

所以要开启char String中的第一个hello

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

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

答案 2 :(得分:0)

像那样。除char hi=hello;以外,char hi=hello.charAt(0)应为break;。 (不要忘记你的{{1}}陈述。

答案 3 :(得分:0)

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

switch (hello.charAt(0)) 

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

中的空间
case 'a '

答案 4 :(得分:0)

以下是一个例子:

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