【问题标题】:Why is the while loop not printing?为什么while循环不打印?
【发布时间】:2018-08-11 07:03:23
【问题描述】:

尝试打印此模式

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

for 和 while 循环不知何故无法以正确的方式工作。 逻辑有问题吗?

       public class Test {

           public static void main(String args[]) {
             for (int i = 1; i >= 4; i++) {
               for (int j = 1; j <= 7; j++) {
                 while (i + j >= 5 && (Math.abs(j - i)) <= 3) {
                   System.out.print("*");
                 }
                 System.out.print(" ");
               }
              System.out.println();
           }

       }

【问题讨论】:

    标签: java logic


    【解决方案1】:

    第一个for循环不正确:

    for(int i=1;i>=4;i++)
    

    这段代码说,将i 设置为1,而i 大于或等于4,则增加i。由于i 为1,因此条件永远不会通过。

    顺便说一句,使用 IDE 将帮助您发现这样的错误,例如 intellij 对这段代码的评价:

    【讨论】:

      【解决方案2】:

      我认为您正在尝试打印问题中提到的中心三角形图案。

      这是打印相同内容的示例程序。

      public class TestCenterTriangle {
      
         public static void main(String args[]) {
            printCenterTriangle(4);
         }
      
         private static void printCenterTriangle(int row) {
             for (int i = 1; i <= row; i++) {
                 for (int space = 1; space <= (row - i); space++) {
                     System.out.print(" ");
                 }
      
                 for (int j = 1; j <= i; j++) {
                     System.out.print("*");
                 }
      
                 for (int k = (i - 1); k >= 1; k--) {
                     System.out.print("*");
                 }
      
                 System.out.println();
      
              }
          }
      }
      

      这是输出

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

      【讨论】:

      • public class TestCenterTriangle() 它的构造函数不是类。
      • 感谢 Prateek !这是拼写错误。现在解决了这个问题。
      • 投反对票的人,请问我可以知道投反对票的原因吗?
      【解决方案3】:
       public class Test{
      
       public static void main(String args[]){
      
        int n =15;
        for(int i=0;i<=n;i+=2){
        for(int k=n-i;k>=0;k--)
         System.out.print(" "); 
         for( int j=1;j<=i+1;j++){
          System.out.print("* ");   
         }
          System.out.println();
          }
        }
       }       
      

      遵循这种方法。你可以得到你的输出:-

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        • 2012-11-07
        • 2015-06-12
        • 2021-09-07
        相关资源
        最近更新 更多