简体   繁体   English

java-打印包含数字9-0的反向三角形

[英]java-Printing Reversed Triangle containing numbers 9-0

Hello guys i need your help here is my code 大家好,我需要您的帮助,这是我的代码

public class act_numTria {
  public static void main(String[] args) {
    int z = 9;
    for(int x = 1; x <= 4; x++) {
      for(int y = 4; y >= x; y--) {
        System.out.print(z);
        z--;
      }
      System.out.print("\n");
    }
  }
}

the output is: 输出为:

9876
543
21
0

but it should be like this 但应该是这样

6789
345
12
0

If you don't want to involve any string operations, you can do this... 如果您不想涉及任何字符串操作,则可以执行此操作...

public class act_numTria {
   public static void main(String[] args) {
      int z = 9;
      for(int x=1;x<=4;x++){
         for(int y=4;y>=x;y--){
            System.out.print(z-y+1);
         }
         z = z - (4 - x);
         System.out.print("\n");
      }
   }
}

Here is a modified code of yours .. you just need to accumulate your digits and then reverse it: 这是您的修改后的代码..您只需要累加数字然后反转:

 public class act_numTria {

    public static void main(String[] args) {
        int z = 9;
        for (int x = 1; x <= 4; x++) {
            StringBuilder sb = new StringBuilder();
            for (int y = 4; y >= x; y--) {
                sb.append(z--);
            }
            System.out.print(sb.reverse().toString() + "\n");
        }

    }
}

Here is another solution to your problem: 这是您的问题的另一种解决方案:

public class act_numTria {

        public static void main(String[] args) {
            int start = 6;
            int diff = 3;
            for (int z = start; diff>=0; z=start) {
                for(int i=z;i<=start+diff;i++) {
                    System.out.print(i);
                }
                System.out.println();
                start-=diff;
                diff--;
            }

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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