2014-11-24 45 views
0

基本上这个游戏要求输入1到52之间的整数,一旦程序运行,它将输出卡片名称和花色,它适用于除52之外的每个整数,这会导致程序崩溃。有没有人有任何想法?排列在纸牌游戏中的问题

public static void main(String[] args) { 

    int i = 0; 
    int[] cards = new int[54]; 

    boolean notZero = true; 

    while (notZero == true) { 

     System.out.println("Please input a number in the range 1-52: "); 

     Scanner sc = new Scanner(System.in); 

     int input = sc.nextInt(); 

     if (input == 0) { 

      break; 

     } else if ((input < 1) || (input > 52)) { 

      System.out.println("Invalid input please try again."); 
     } else { 
      cards[i] = input; 
     } 
     i++; 

    } 
    outputCards(cards, i); 
} 

public static void outputCards(int[] cards, int arraySize) { 

    String[] suit = {"Hearts", "Diamonds", "Clubs", "Spades"}; 
    String[] rank = {" ", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10","Jack", "Queen", "King", 
         "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", 
         "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", 
         "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; 

    for (int j = 0; j < arraySize; j++) { 

     System.out.println(rank[cards[j]] + " of " + suit[(int) (cards[j]/13)]); 

    } 

} 
+2

当'cards [j] == 52',然后是'52/13 - > 4',这是超过你的西装阵列的末尾,使'suit [4]'你的问题 – 2014-11-24 16:47:23

回答

0

这是因为数组的索引从0开始的,所以你可能要问,从0输入 - 51.另一个问题是,你正在使用print语句:

suit[(int) (cards[j]/13)]) 

这意味着,由于您的输入标准,您允许52到由用户输入所以这将评估为

suit[52/13];//suit[4] 

尽管你有西服四个元素为好,但如我上述数组索引开始从所述0,所以可以查询ARR在0-3之间。所以这会导致数组索引超出界限的异常。

+1

我添加了一个空元素在阵列的开始处理。 – Dirty 2014-11-24 16:45:59

+0

确实如此,但看到您的main方法中有'int i = 0;',并且正在将用户输入从第0个元素设置到数组中。 – SMA 2014-11-24 16:47:07

0

的第1张卡的INDEX = 0

第52卡的指数= 51

,所以你要做的输入的号码-1

+0

nope;他在查找数组的索引0处有一个空字符串元素。 – 2014-11-24 16:56:11

+0

你是对的,问题下面的评论是正确的解决方案 – 2014-11-24 17:04:18

0

你不应该增加索引i++当输入无效;此外,您应该在while循环中检查用户输入的值不超过52个。

if (input == 0) { 
    break; 
} else if ((input < 1) || (input > 52)) { 
    System.out.println("Invalid input please try again."); 
} else { 
    cards[i] = input; 
    if (i++ > 51) break; 
} 

此外,在适合的情况下,你可以在outputCards()方法中得到一个数组索引超出边界,当我= 52。这是因为如果用户插入52个值,52/13 = 4和suit[4]超出了只有0..3个项目的范围。