Java多维数组,如何获取要打印的列数?
我的代码在下面,我的任务是 正如您在我的代码中看到的,我将数组设置为[playerCount][5],我认为这会导致问题,但我不确定如何修复它。有时可能有5列,有时可能只有2、3、4列。还有多行,可以是1,2,3,无穷大。我似乎不知道如何获得列中的行总数,因此稍后我可以将这些行中的值相加以获得总和Java多维数组,如何获取要打印的列数?,java,arrays,multidimensional-array,Java,Arrays,Multidimensional Array,我的代码在下面,我的任务是 正如您在我的代码中看到的,我将数组设置为[playerCount][5],我认为这会导致问题,但我不确定如何修复它。有时可能有5列,有时可能只有2、3、4列。还有多行,可以是1,2,3,无穷大。我似乎不知道如何获得列中的行总数,因此稍后我可以将这些行中的值相加以获得总和 import java.util.Scanner; class ASgn8 { public static void main(String[] args) { Scanner sc
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;
}
}
}
}
import java.util.Scanner;
ASgn8类
{
公共静态void main(字符串[]args)
{
扫描仪扫描=新扫描仪(System.in);
系统输出打印(“有多少玩家?”);
int playerCount=scan.nextInt();
scan.nextLine();
字符串[]playerNames=新字符串[playerCount];
骰子[][]骰子数组=新骰子[playerCount][5];
对于(int i=0;i
看看这个例子:
String[][] array = new String[5][6];
System.out.println(array.length);
System.out.println(array[0].length);
我想一切都会很清楚。我不太清楚你的意思,但你会得到
diceArray.length
的列和diceArray[0]的行。length
会获取存储在数组中的一个数组并告诉它的大小。多维数组不是真正的多维数组,但更像是包含数组的数组,因此需要获取一个内部数组来确定其大小
但是,您可能应该改用ArrayList[],因为普通java数组无法调整大小。ArrayList可以,所以您可以
ArrayList diceArray=新建ArrayList()[playerNum]
然后使用for循环初始化ArrayList,然后使用diceArray[playerNum].size()获得大小。检查示例教程。这是有道理的,但是我的数组设置为[5],并且一直延续到最后,只是我不知道如何将其声明为用户想要滚动的数量,直到循环结束,这是未知的,您知道有什么方法来修复吗?