-1

所以我正在为我的 Java 类做这个作业,我一直遇到这个错误"unreachable code",我不知道如何修复这个错误,甚至找不到它发生的原因。请帮忙!

public static void main(String[] args)
    {

        int suit;
        int cardNumber;


        Random generator = new Random();


          suit = generator.nextInt (4)+1;;
            String suitString;
            switch (suit) {
                case 1:  suitString = "hearts!";
                         break;
                case 2:  suitString = "diamonds!";
                         break;
                case 3:  suitString = "clubs!";
                         break;
                case 4:  suitString = "spades!";
                         break;


         cardNumber = generator.nextInt (13) +1;; //unreachable code
            String cardNumberString;
            switch (cardNumber) {
                case 1: cardNumberString = "ace";
                    break;
                case 2: cardNumberString = "2";
                break;
                case 3: cardNumberString = "3";
                break;
                case 4: cardNumberString = "4";
                break;
                case 5: cardNumberString = "5";
                break;
                case 6: cardNumberString = "6";
                break;
                case 7: cardNumberString = "7";
                break;
                case 8: cardNumberString = "8";
                break;
                case 9: cardNumberString = "9";
                    break;
                case 10: cardNumberString = "10";
                break;
                case 11: cardNumberString = "11";
                break;
                case 12: cardNumberString = "12";
                break;
                case 13: cardNumberString = "13";
                break;
4

2 回答 2

5

switch第一个 . 之后的语句没有右括号case 4。下一条语句在 the 之后,break这意味着它无法访问。

switch (suit) {
            case 1:  suitString = "hearts!";
                     break;
            case 2:  suitString = "diamonds!";
                     break;
            case 3:  suitString = "clubs!";
                     break;
            case 4:  suitString = "spades!";
                     break;
} // Need to close the switch statement
于 2013-09-18T21:46:02.857 回答
2

您必须关闭括号。在未关闭之后,代码无法访问case 4{

switch (suit) {
            case 1:  suitString = "hearts!";
                     break;
            case 2:  suitString = "diamonds!";
                     break;
            case 3:  suitString = "clubs!";
                     break;
            case 4:  suitString = "spades!";
                     break;
} //Here
于 2013-09-18T21:46:25.480 回答