2017-06-16 96 views
-1

我对Java很陌生,正在编写一个从2维数组中随机选择一个元素的方法。'随机'返回值不在数组中?

这个想法是,你给它一个由52张卡片组成的2维数组(4套房中的13张卡片),然后你随机选择其中的4张并返回它们的总和。

该程序似乎大部分工作正常,但有时它会返回卡“钻石0”。这不是我给这个方法的数组中的一个元素,所以不太确定这里发生了什么。

我会重现最下方的相关代码:

int [][] cards = {{2,3,4,5,6,7,8,9,10,11,12,13,14},{2,3,4,5,6,7,8,9,10,11,12,13,14}, 
      {2,3,4,5,6,7,8,9,10,11,12,13,14},{2,3,4,5,6,7,8,9,10,11,12,13,14}}; 
    int num1 = randomPick(cards); 
     sum = sum+num1; 

    switch(num1){ 
     case 11: System.out.print("Jack of "+ suite+", "); 
      break; 
     case 12: System.out.print("Queen of "+ suite+", "); 
      break; 
     case 13: System.out.print("King of "+ suite+", "); 
      break; 
     case 14: System.out.print("Ace of "+ suite+", "); 
      break; 
     default: System.out.print(num1+" of "+ suite+", "); 
      break;} 


    public static int randomPick(int[][] array){       
    int randrow = new Random().nextInt(array.length);    
    int randcol = new Random().nextInt(array[randrow].length);  
    switch (randrow){ 
    // Each row corresponds to a different suite of cards 
    case 1: 
     suite= "spades"; 
     break; 
    case 2: 
     suite = "hearts"; 
     break; 
    case 3: 
     suite = "diamonds"; 
     break; 
    case 0: 
     suite = "clubs"; 
     break; 
    }  
    int element =array[randrow][randcol]; 
    return(element);}  

正如你可以看到0是不是传递给方法的数组中的元素,它是如何有时返回0?

+2

您的一些示例代码丢失 - 你粘贴不能编译什么。如果您共享[MCVE](https://stackoverflow.com/help/mcve),我们可以直接运行您的代码并尝试复制该问题。 – dimo414

+2

卡片有“套装”,而不是“套装”。 –

回答

1

如果在每次调用中向其传递相同的cards数组,则randomPick的上述实现将不返回0

它看起来像cards数组得到修改的地方下线和randomPick被更新的数组调用?我会建议在randomPick方法添加日志记录或sysout如果element是0,例如:

int element =array[randrow][randcol]; 
if(element == 0){ 
    for(int[] arrayElement : array){ 
     System.out.println(Arrays.toString(arrayElement)); 
    } 
}