Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

Java For Loop Number Grid

I am trying to make a number grid using a Java for-loop but I have difficulty making it aligned and following the pattern.

The output that I want to see is:

5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21

I've been watching youtube tutorials and articles about Java for-loops but I can't find any idea to solve this. I am currently stuck with this code:

int j=5;
int up1=14, up2=6;

for(int u=1; u<=5; u++)
{
    for(int s=1; s<=5; s++)
    {
        System.out.print(j+"");
        j--;


    }
    System.out.println("");

    if(u%2==0){
        j+=up1;
    }else{
        j+=up2;
    }
}

Its output is:

5   4   3   2   1   
6   5   4   3   2   
15  14  13  12  11  
16  15  14  13  12  
25  24  23  22  21

I have heard about int update but I have no idea how to apply it in my code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You forgot to invert the increment(-1/+1) every line. Then you need only to adjust up1 and you're fine

    int j = 5;
    int inc = -1;
    int up1 = 4, up2 = 6;

    for (int u = 1; u <= 5; u++) {
        for (int s = 1; s <= 5; s++) {
            System.out.print(j + "");
            j += inc;

        }
        System.out.println("");

        inc = -inc;
        if (u % 2 == 0) {
            j += up1;
        } else {
            j += up2;
        }
    }

Output:

5   4   3   2   1   
6   7   8   9   10  
15  14  13  12  11  
16  17  18  19  20  
25  24  23  22  21

Your problem with the alignment might be that you want leading spaces for the single digits, then use this for the print:

    System.out.print(String.format("%2d", j));

Output

 5   4   3   2   1  
 6   7   8   9  10  
15  14  13  12  11  
16  17  18  19  20  
25  24  23  22  21  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...