在字符串中使用switch

时间:2010-05-29 09:55:27

标签: java switch-statement

尝试在字符串中使用switch,首先将字符串转换为char然后应用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");
 **/

4 个答案:

答案 0 :(得分:4)

请查看有关此主题的excellent article

答案 1 :(得分:1)

请注意,在Java 7中切换字符串将为supported

答案 2 :(得分:1)

目前,您switch上无法String。语言规范明确了switch的内容:

JLS 14.11 The switch statement

SwitchStatement:
      switch ( Expression ) SwitchBlock
     

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

根据您的目的,您switch的{​​{1}} char可以String

    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 :(得分:0)

您无法打开char []类型。打开char [0]并使用case 'J':等等(尽管 - 因为几个月以相同的字母开头,算法将是次优的)