Java程序停止然后在到达循环时停止

时间:2015-10-20 23:16:03

标签: java loops

我有一个程序(用Java编写),当它到达for或while循环时,它会停止约2秒然后完全停止。这是代码:

import javax.swing.*;
public class numberCruncher
{
   public static int number,guess,x;
   public static void main(String[] argv)
   {  
      number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):"); 
      System.out.print("1");
      test();
   }
   public static void test()
   {  
      boolean correct = false;
      System.out.print("2");
      //while(correct=false)
      for(x=0;x>999999999;x++)
      {
         //x++;
         System.out.print("3");
         guess=cleanUsage.random(0,99999);
         System.out.print("4");
         System.out.println(" "+guess);
         if (guess==number)
         {
            System.out.println();
            System.out.println("Correct number guessed in "+x+" tries");
            //correct = true;
         }
      }
   }
   public static int enterIntGUI(String prompt)
   {
      String tempString = JOptionPane.showInputDialog(prompt);
      int temp = Integer.parseInt(tempString);
      return temp;
   }
}

你可以看到我对while循环的东西有评论。此外,我已经放入了4个println语句,我认为它会被卡住,它打印1和2,但不是3.这是我的cleanUsage类包含随机数生成器的部分:

public static int random(int min, int max)
    {
        int range = max - min + 1;
        int number = (int) (range * Math.random() + min);
        return number;
    }

我问过其他人,他们无法弄明白。如果你能帮助我,那就太好了。

2 个答案:

答案 0 :(得分:1)

它不会打印34,因为条件x>999999999最初为false,因此永远不会输入for循环。我认为你的意思是<

另请注意,您可以使用break而不是correct = true退出循环。

答案 1 :(得分:0)

import javax.swing.*;
public class numberCruncher
{
   public static int number,guess,x;
   public static void main(String[] argv)
{  
  number=enterIntGUI("Enter a number for the\ncomputer to crack\n(5 digits maximum):"); 
  System.out.print("1");
  test();
}
public static void test()
{  
   boolean correct = false;
   System.out.print("2");
   //while(correct==false)  // equality test, not assignment
   for(x=0;x<999999999;x++) //2nd argument is continue while false
   {
      //x++;
      System.out.print("3");
      guess=cleanUsage.random(0,99999);
      System.out.print("4");
      System.out.println(" "+guess);
      if (guess==number)
      {
        System.out.println();
        System.out.println("Correct number guessed in "+x+" tries");
        //correct = true;
      }
   }
}
public static int enterIntGUI(String prompt)
   {
    String tempString = JOptionPane.showInputDialog(prompt);
    int temp = Integer.parseInt(tempString);
    return temp;
   }
}