2015-11-30 34 views
-2

我的代码如下,我的任务是Java多维数组,如何获得打印列数量?

enter image description here

正如你可以在我的代码中看到的,我有数组设置为[playerCount] [5],我认为这是造成问题,但林不确定如何解决它。有时可能会有5列,有时可能只有2,3,4。也有多行,可能是1,2,3,无穷大。我似乎无法弄清楚如何获得列的总行数,所以后来我可以在这些行中添加值来获得总和。

import java.util.Scanner; 

class ASgn8 
{ 

public static void main(String[] args) 
{ 

    Scanner scan = new Scanner(System.in); 

    System.out.print("How many players? "); 
    int playerCount = scan.nextInt(); 
    scan.nextLine(); 
    String[] playerNames = new String[playerCount]; 
    Die[][] diceArray = new Die[playerCount][5]; 

    for(int i = 0; i < playerCount; i++) 
    { 
     System.out.print("What is your name: "); 
     playerNames[i] = scan.nextLine(); 
    } 

    int randomNum = (int)(Math.random() * (30-10)) +10; 
    System.out.println(randomNum); 
    int userChoice = 1; 

    for(int i = 0; i < playerCount; i++) 
    { 

     int j=0; 
     System.out.println(playerNames[i] + "'s turn!"); 

     while(userChoice != 2 && j < 5) 
     { 
      Die roll2 = new Die(); 
      roll2.roll(); 
      System.out.println(roll2);    
      diceArray = new Die[i][j];    
      System.out.println("Again? 1= yes, 2=no"); 
      userChoice = scan.nextInt(); 
      j++; 

     } 

     if(userChoice == 2) 
     { 
      userChoice = 1; 

     } 

    } 

} 
} 

回答

0

请看下面的例子:

String[][] array = new String[5][6]; 
System.out.println(array.length); 
System.out.println(array[0].length); 

我想一切都会清楚的。

+0

它是有道理的,但是我的数组被设置为[5]并且它结束了,只是我不知道如何将它声明为用户想要滚动的数量,直到循环才知道它的数量你知道有什么办法解决这个问题吗? –

1

我不太清楚你的意思,但你会得到diceArray.length列和diceArray[0].length行,其中一个数组存储在数组中,并告诉它的大小。多维数组并不是真正的多维数组,但更像是包含数组的数组,因此您需要获取内部数组中的一个来告诉它的大小。

但是,您可能应该使用ArrayList [],因为普通的java数组不能调整大小。 Arraylists可以,所以你可以做

ArrayList<int> diceArray = new ArrayList()[playerNum]

然后使用for循环初始化ArrayLists,然后使用diceArray [playerNum] .size()获取大小。检查例如this教程。