Java War卡游戏回合

时间:2014-03-26 16:20:16

标签: java arrays

每当我运行代码时,如果任何玩家获得王牌,国王,王后或杰克,我会收到以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Card.getCard(Card.java:19)
    at Card.main(Card.java:37)

这是我到目前为止的代码:

public class Card  
{  
    String suit;  
    String rank;    
    int getCard; 
    int a;  
    int b;
    int getSuit;

    public Card(){    
        String [] xSuit = {"Clubs","Diamonds","Hearts","Spades"};  
        String [] xRank = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};  
        a = ((int)(Math.random() * 4));  
        b = ((int)(Math.random() * 13));  
        suit = xSuit[a];  
        rank = xRank[b];  
    }  
    int getCard(){  
        getCard = Integer.parseInt (rank);  
        return getCard;  
    }
    int getSuit(){
        getSuit = Integer.parseInt (suit);
        return getSuit;     
    }


public static void main(String[] args)  
{  
     Card player = new Card();  
     Card player2 = new Card();  

    System.out.println("WAR");  
    System.out.println("--------------");
    System.out.println("You played the " + player.rank + " of " + player.suit);
    System.out.println("Player 2 played the " + player2.rank + " of " + player2.suit);  
    if (player.getCard() > player2.getCard()){  
         System.out.println("You win!");    
     }  
     else if (player.getCard() < player2.getCard()){  
         System.out.println("Player 2 wins!");  
     }
     else if (player.getCard() == player2.getCard()){
         if(player.getSuit() > player2.getSuit()){
                 System.out.println("You win!");
         }
         else if(player.getSuit() < player2.getSuit()){
         System.out.println("Player 2 wins!");
         }
         else{
             System.out.println("There was a draw.");
         }
      }
 }  

}

我有没有办法让它成为“Jack”和“Queen”而不会出错?

1 个答案:

答案 0 :(得分:0)

您无法将非数字文本传递到parseInt()方法调用,因为它实际上不是数字。另一种方法是尝试这样做:

String suit;  
String rank;     
int a;  
int b;
int getCard;
int getSuit;

public Card(){    
    String [] xSuit = {"Clubs","Diamonds","Hearts","Spades"};  
    // xRank array removed because I don't think you need it anymore. 
    a = ((int)(Math.random() * 4));  
    b = ((int)(Math.random() * 13) + 1);  
    suit = xSuit[a];
    switch(b) {
        case 1:
            rank = "Ace";
            break;
        case 11:
            rank = "Jack";
            break;
        case 12:
            rank = "Queen";
            break;
        case 13:
            rank = "King";
            break;
        default:
            rank = Integer.toString(a);
            break;
    }
} 

int getCard(){    
    return b;  // this will probably be unnecessary now, you'd probably also want a better name for this numeric card value...
}