繁体   English   中英

如何在Java中使用扫描仪打印二维整数数组

[英]how to print 2d integer array using scanner in java

System.out.println("Enter the  No. of rows to dispaly in 2d");
Scanner n = new Scanner(System.in);
double r = n.nextInt();
System.out.println("Enter the  No. of cols to dispaly in 2d");
Scanner v = new Scanner(System.in);
double q= v.nextInt();
System.out.println("Enter the data");
Scanner sc = new Scanner(System.in);
int d = sc.nextInt();
int  x[][]={};
int z,y=0;

for ( y=0; y<r.length; y++)

{

   for (z=0; z<q.length; z++)

    {

        x[y][z] = sc.nextInt();

    }

} 



for ( int m=0; m<x.length; m++)

{    for(int p=0; p<x.length; p++)

    {  

        System.out.println("x[" +m + "][" +p +"]=" +x[m][p]);

    }

}
for(int p=0; p<x.length; p++)

是不正确的, p需要从0x[m].length

您需要这样的东西:

for(int m = 0; m < x.length; m++)
{    
    for(int p = 0; p < x[m].length; p++)
    {  
        System.out.println("x[" + m + "][" + p +"]=" +x[m][p]);
    }
}

2d数组是数组的数组,因此第二个for循环将看到1d数组,它们也具有length属性。

您的代码有问题:

System.out.println("Enter the  No. of rows to dispaly in 2d");
Scanner n = new Scanner(System.in);
double r = n.nextInt();//why use double? use int r=n.nextInt();
System.out.println("Enter the  No. of cols to dispaly in 2d");
Scanner v = new Scanner(System.in);//why create another Scanner object, use the old one.
double q= v.nextInt();//int here again
System.out.println("Enter the data");
Scanner sc = new Scanner(System.in);//not another scanner
int d = sc.nextInt();
int  x[][]={};
int z,y=0;

for ( y=0; y<r.length; y++)//what's with the length of a double?

{

   for (z=0; z<q.length; z++)

    {

        x[y][z] = sc.nextInt();

    }

} 



for ( int m=0; m<x.length; m++)

{    for(int p=0; p<x.length; p++)//need to use x[m].length

    {  

        System.out.println("x[" +m + "][" +p +"]=" +x[m][p]);

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM