【问题标题】:using switch in strings在字符串中使用 switch
【发布时间】:2012-08-01 12:25:37
【问题描述】:

尝试通过首先将字符串转换为 char 然后应用 switch 来在字符串中使用 switch,但仍然没有这样做..这是我的代码..

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JOptionPane;

class HappyBirthday {

    public static void main(String[] args) throws IOException {
        String Month;
        char[] Months = Month.toCharArray();
        BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please enter your month.");

        Month = JOptionPane.showInputDialog("enter month");
        String month1 = { "January", "feb"};
        char[] month2 = month1.toCharArray();

        // String s=month1.equals(Month);
        // System.out.print(month2Array[0]);
        switch (month2) {

        case 0:
            System.out.println("kool");
            break;

        case 1:
            System.out.println("not kool");
            break;
        default:
        }
    }
}
/**
 * if (month1[1].equals(Month)) System.out.println("kool"); else
 * if(month1[0].equals(Month)) System.out.println("kooooooooooooool"); else
 * System.out.println("Big kooooool");
 **/

【问题讨论】:

  • 我差点否决这个问题,仅仅因为代码格式化是一场灾难!下次发帖前请花点时间清理一下。
  • (skaffman 用于清理的虚拟 +1 ;-))
  • 在 switch 中使用字符串是 java7 的一部分

标签: java switch-statement


【解决方案1】:

看看这个excellent article关于这个主题。

【讨论】:

    【解决方案2】:

    目前,您不能在 String 上使用 switch。语言规范很清楚你可以在switch 上做什么:

    JLS 14.11 The switch statement

    SwitchStatement:
          switch ( Expression ) SwitchBlock
    

    Expression 的类型必须是 charbyteshortintCharacterByteShortInteger 或 @9876543 类型, 或发生编译时错误。

    根据您想做什么,您可以在char 的每个charswitch

        String s = "Coffee, tea, or me?";
        int vowelCount = 0;
        int punctuationCount = 0;
        int otherCount = 0;
        for (char letter : s.toUpperCase().toCharArray()) {
            switch (letter) {
                case 'A': 
                case 'E':
                case 'I':
                case 'O':
                case 'U':
                    vowelCount++;
                    break;
                case ',':
                case '.':
                case '?':
                    punctuationCount++;
                    break;
                default:
                    otherCount++;
            }
        }
        System.out.printf("%d vowels, %d punctuations, %d others",
            vowelCount, punctuationCount, otherCount
        ); // prints "7 vowels, 3 punctuations, 9 others"
    

    【讨论】:

      【解决方案3】:

      请注意,在 Java 7 中打开字符串将是 supported

      【讨论】:

      【解决方案4】:

      您不能打开 char[] 类型。打开 char[0] 并使用 case 'J': 等等(尽管 - 因为有些月份以相同的字母开头,所以算法可能不是最佳的)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多