【问题标题】:How do I use a char as the case in a switch-case?如何在 switch-case 中使用 char 作为 case?
【发布时间】:2011-08-02 00:23:06
【问题描述】:

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

【问题讨论】:

    标签: java switch-statement character


    【解决方案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 从字符串中获取一个字符,你可以打开它们,因为char 是一个整数类型。

      所以要打开String中的第一个charhello

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

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

      【讨论】:

        【解决方案3】:

        这是一个例子:

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

        【讨论】:

          【解决方案4】:

          这样。除了char hi=hello; 应该是char hi=hello.charAt(0)。 (不要忘记您的 break; 声明)。

          【讨论】:

            【解决方案5】:

            当变量是字符串时使用字符是行不通的。使用

            switch (hello.charAt(0)) 
            

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

            case 'a '
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-05-14
              • 1970-01-01
              • 2023-02-25
              • 1970-01-01
              • 2016-09-26
              相关资源
              最近更新 更多