【问题标题】:Drawing a grid using nested loops使用嵌套循环绘制网格
【发布时间】:2014-09-01 06:47:17
【问题描述】:

我正在尝试绘制如下所示的网格:

1

12

123

1234

12345

123456

1234567

12345678

123456789

这是我的代码:

public class shape { 
    public static void main(String[] args){

        int number = 1, newNumber, zMax = 1;
        String numString = "1";

        for (int i = 1; i <= 9; i++){

            for (int z = 0; z < zMax; z++){

                System.out.print(numString);
                number = number + 1;
                numString += Integer.toString(number);
            }
            System.out.println("");
            if (zMax <= 9)
                zMax++; 
        }
    }
}

它会打印出如下内容:

1

12123

121231234

12123123412345

它在正确的轨道上,但我不知道出了什么问题......请帮助!

【问题讨论】:

    标签: java loops nested


    【解决方案1】:

    编辑:错误理解问题,更正它。

    您的数字重复的原因是您的第二个循环。您要么需要重新初始化 numstring,要么重用旧的,只添加新的数字。

    public class shape { public static void main(String[] args){
    
        String numString = "";
    
        for (int i = 1; i <= 9; i++){
            numstring = numstring + i;
            System.out.println(numstring);
        } 
    
    }
    

    【讨论】:

    • 不...我的意思是,我的代码将打印出更像这样的内容:1 12123 121231234 12123123412345...等...这不是我想要的,我希望它更像:1 12 123 1234
    【解决方案2】:
    int start = 1;
    int max = 10;
    for(int i = 1; i < max; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }
      System.out.println("");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2019-07-15
      • 1970-01-01
      • 2021-01-12
      • 2018-08-10
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多