【问题标题】:Java Loop Number square ( reversed order ) each line [closed]Java循环号正方形(倒序)每行[关闭]
【发布时间】:2020-10-27 13:14:42
【问题描述】:

所以我想知道如何制作这个......

我在互联网上找到了这个代码,它给了我一个数字正方形图案

import java.util.Scanner;

public class Square {


    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        int a;
        
        System.out.print("Input :");
        a = sc.nextInt();
        
        for (int iOuter = 1; iOuter <= a; iOuter++) {
            
            for (int i = 1; i <= a; i++) {
                
                System.out.print(i);
                
            }
            System.out.println();
        }

    }
    
}

如果我输入 5,这是输出

12345
12345
12345
12345
12345

我正在寻找这个输出

12345
54321
12345
54321
12345

提前致谢

【问题讨论】:

  • 除了您的要求外,还请说明您的问题。您尝试了哪些解决方案?为什么它们不起作用?

标签: java loops numbers


【解决方案1】:

试试这个代码:

for (int iOuter = 1; iOuter <= a; iOuter++) {
            
            for (int i = 1; i <= a; i++) {
                if (iOuter % 2 == 0) { // if is even
                    System.out.print(1 + a - i);
                }else {// if is odd
                    System.out.print(i);
                }
            }
            System.out.println();
        }

这将使奇数行和偶数行不同。

【讨论】:

    【解决方案2】:

    这只是将值转换为字符串并使用 StringBuilder 将其反转。

    int val = 54321;
    StringBuilder sb = new StringBuilder().append(val);
    for(int i = 0; i < 5; i++) {
       System.out.println(sb.reverse());
    }
    

    打印

    12345
    54321
    12345
    54321
    12345
    

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 2016-01-29
      • 2014-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多