Java 为什么数组1的长度大于预期值?
我试图打印出二维数组的列大小和行大小。我的程序可以编译,但可以打印:Java 为什么数组1的长度大于预期值?,java,arrays,Java,Arrays,我试图打印出二维数组的列大小和行大小。我的程序可以编译,但可以打印: Welcome to DrJava. Working directory is C:\Users\mulk\Downloads > run Lab4 Print out the rowsize: 4.0 Print out the columnsize: 4.0 > 行大小不应该是3.0吗?我从零开始数 /* * Purpose: Prints the row and column averages
Welcome to DrJava. Working directory is C:\Users\mulk\Downloads
> run Lab4
Print out the rowsize: 4.0
Print out the columnsize: 4.0
>
行大小不应该是3.0吗?我从零开始数
/*
* Purpose: Prints the row and column averages
*/
class Lab4
{
public static void main(String[] args)
{
int [][] scores = {{ 20, 18, 23, 20, 16 },
{ 30, 20, 18, 21, 20 },
{ 16, 19, 16, 53, 24 },
{ 25, 24, 22, 24, 25 }};
outputArray(scores);
}
public static void outputArray(int[][] array)
{
double rowsize = 0.0;
double columnsize= 0.0;
for(double i=0.0;i <= array.length;i++)
{
rowsize = array.length;
}
System.out.println("Print out the rowsize: " +rowsize);
for (double j = 0; j <=array[0].length; j++)
{
columnsize = array.length;
}
System.out.println("Print out the columnsize: " +columnsize);
}
}
/*
*用途:打印行和列的平均值
*/
Lab4类
{
公共静态void main(字符串[]args)
{
int[][]分数={{20,18,23,20,16},
{ 30, 20, 18, 21, 20 },
{ 16, 19, 16, 53, 24 },
{ 25, 24, 22, 24, 25 }};
输出阵列(分数);
}
公共静态void输出阵列(int[][]数组)
{
双行大小=0.0;
双柱尺寸=0.0;
对于(double i=0.0;i2D数组只是一个数组数组。因此,要确定有多少行,我们需要使用arrayName.length,然后要确定每列中有多少项,我们必须转到第一行(数组),并通过arrayName[0].length来确定长度
因此,正如您所看到的,您正在使用的代码将发现有两行。它应该如下所示:
double rowsize = 0.0;
double columnsize= 0.0;
rowsize = array.length;
System.out.println("Print out the rowsize: " +rowsize);
if(rowsize >= 1){
columnsize = array[0].length;
}
System.out.println("Print out the columnsize: " +columnsize);
我希望这已经解决了您的问题:)大小从1开始,索引从0开始。如果您有一行,它可能被索引为第0行(取决于语言),但我们仍然说“大小”是1。正如Eric已经说过的,但是…您可以只System.out.println(“行:“+scores.length”);
和System.out.println(“cols:+scores:+scores[0]。长度);