有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java请帮助我完成这个while循环

请纠正我的错误

    package com.company;
    
    public class practice2 {
        public static void main(String[] args) {
    
            int a = 5;
    
            while (a > 0) {
                while (a>0) {
                    System.out.print("*");
                    a--;
                }
                a--;
            }
        }
    }

上面的代码只适用于一个,下面的代码适用于一个。。。。。。。。。为什么我需要将它分配给一个新变量,以便在新循环中使用它

    package com.company;
    
    public class practice2 {
        public static void main(String[] args) {
    
            int a = 5;
    
            while (a > 0) {
                a=b;
                while (b>0) {
                    System.out.print("*");
                    b--;
                }
                a--;
            }
        }
    }

要打印:

*****
****
***
**
*

这不是一个家庭作业问题,我只是无法理解这个概念


共 (3) 个答案

  1. # 1 楼答案

    试试这个

     class HelloWorld {
          public static void main(String[] args) {
              int i=0,j=0,a=5;
              while (a > i) {
              j=i;
              while (a>j) {
                System.out.print("*");
                j++;
              }
              System.out.println();
              i++;
              }
            }
        }
    

    输出:

    *****
    ****
    ***
    **
    *
    
  2. # 2 楼答案

    您的代码现在将打印以下内容:

    *
    *
    *
    *
    *
    

    因为您还没有指定每行需要打印多少次星星

    要解决这个问题,只需将System.out.print("*");更改为System.out.print("*" * a);

    这意味着您需要在每个循环中打印字符*“a”次。由于a的值在减小,你的问题就解决了

    也可以尝试使用for循环而不是while循环。这个website会帮你的

  3. # 3 楼答案

    您可以只使用一个循环来执行此操作,并使用.repeat()方法来重复星号

    编辑:调用一个方法来完成这项工作更好:)

    public class MyClass {
        public static void main(String args[]) {
            printStarsTriangle(5);
        }
        static void printStarsTriangle(int n) {
            for(int i = n;i > 0; i ) {
                System.out.print("*".repeat(i) + (i != 1 ? "\n" : ""));
            }
        }
    }
    

    输出:

    *****
    ****
    ***
    **
    *