0
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]);

    }

}
4

2 回答 2

0
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]);
    }
}

二维数组是数组的数组,因此第二个 for 循环看到也具有长度属性的一维数组。

于 2013-09-26T09:08:55.140 回答
0

您的代码存在问题:

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]);

    }

}
于 2013-09-26T09:15:39.857 回答