【问题标题】:Why is this creating an infinite loop?为什么这会造成无限循环?
【发布时间】:2014-11-07 19:49:19
【问题描述】:

我正在尝试使用方法来构建一个沙漏图形,该图形是基于 3 到 10 之间的用户输入的特定大小。但是,当我运行该程序时,我得到了一个无限循环。

   public static void main(String[] args){

   int height;

   Scanner keyboard = new Scanner(System.in);
   System.out.println("Enter an integer between 3 and 10 to control the" +
                       " heigth of the hour glass: ");
   height = keyboard.nextInt();                    


    line();
    topHalf();
    bottomHalf();
    line();

 }

public static void line() {

  System.out.println("+");
  for (int i = 1; 1<= 10; i++){
     System.out.println("-");

     System.out.println("+");    
       }   
    }


    public static void topHalf()
     {
          for(int line = 1; line <= 3; line++){
          System.out.println("|");
          for (int i = 1; i<= (line - 1); i++){
             System.out.println(" ");
          }
          System.out.println("\\");
          for (int i = 1; i <= (6 - 2 * line); i++){  
             System.out.println(".");
          }
          System.out.print("/");
          for (int i = 1; i <= (line - 1); i++){
             System.out.println(" ");
          }
          System.out.println("|");    
        }
    }

    public static void bottomHalf()
    {
       for (int line = 1; line <= 3; line++){
          System.out.println("|");
          for (int i = 1; i <= (3 - line); i++){
             System.out.println(" ");
          }
          System.out.println("/");
          for (int i = 1; i <= 2 * (line - 1); i++){
             System.out.println(".");
          }
          System.out.println("\\");
          for (int i = 1; i <= (3 - line); i++){
             System.out.print(" ");
          }
        }
    }

 }

我真的不知道发生了什么,但我确定它不是沙漏形状。当我运行它时唯一发生的事情是 + 然后 - 的无限循环。非常感谢任何帮助,谢谢!

【问题讨论】:

    标签: java infinite-loop


    【解决方案1】:

    对于for 循环,您的条件中有1 而不是i - 1 &lt;= 10 始终为真,因此是无限循环。你想改变:

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

    到这里:

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

    【讨论】:

    • 你知道为什么它只打印一个代码行的符号而不是创建图片吗?
    • @Drewmeister96 System.out.println 打印一行。
    猜你喜欢
    • 1970-01-01
    • 2017-09-21
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多