[英]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
需要從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屬性。
您的代碼有問題:
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.