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]);
}
}
答案 0 :(得分:0)
for(int p=0; p<x.length; p++)
不正确,p
需要从0
转到x[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属性。
答案 1 :(得分: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]);
}
}