简体   繁体   中英

Filling a 2D Array using two for loops

I have a homework assignment to do, and one of the tasks involves filling a 10 by 3 array with values using only a for loop. The values are supposed to range from 25 to 250, incrementing by 25 each time. The first two columns should show this behaviour, however the third column should only have 5000 as it's entry. Here is a rough "diagram" to show how it is supposed to look:

25 25 5000

50 50 5000

75 75 5000

etc...

So far I have put this as my code, but cannot seem to figure out where to go from here.

    import java.util.ArrayList;    
    public class Array {    
    private static void PrintArray(int[][] Arr) 
    {
        for(int i=0;i<Arr.length;++i)
        {
            for(int j=0;j<Arr[i].length;++j)
            {
                System.out.print(Arr[i][j] + " ");
            }
            System.out.println();
        }
    }


    public static void main(String args[])
    {
        int Arr [][] = new int [10][3],i,j;

        for(i=0;i<Arr.length;++i)
        {
            for(j=0;j<Arr[i].length;++j)
            {
                Arr[i][0] = i*25;
            }
        }
        PrintArray(Arr);        
    }
}

Anybody have any ideas?

you should replace second for with:

for (j = 0; j < Arr[i].length; ++j) {
 Arr[i][j] = (i + 1) * 25;
    if (j == Arr[i].length-1) {
       Arr[i][j] = 5000;
   }
}

You forgot to fill in other columns excepting first in the inner loop of main method, change:

Arr[i][0] = i*25;

to (for example):

int v = (i+1)*25;
Arr[i][0] = v;
Arr[i][1] = v;
Arr[i][2] = 5000;

Also your code contains a couple of code style errors, such as curly braces, naming of variables not in camel case, etc. Get familiar with Java code conventions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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