2016-08-31 45 views
0
import java.util.Scanner; 
import static java.lang.System.out; 

public class TestingStuf2 { 

    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 

      out.println("Enter a number"); 

      int number = keyboard.nextInt(); 

     while (number < 10) { 
      if (number < 10) { 
       out.println("This number is too small."); 
       keyboard.nextInt(); 
      }else{ 
       out.println("This number is big enough."); 
      }  
     } 
     keyboard.close(); 
    } 

} 

我只是有点麻烦循环这段代码。我刚开始学习Java,这些循环一直困扰着我。当我运行这个程序时,如果输入的数字小于10,我会看到“”这个数字太小“的消息,然后它允许我再次输入,但是如果我输入一个大于10的数字,如果我输入的第一个数字大于10,我根本没有收到消息,程序刚刚结束,为什么会发生这种情况?我怎样才能让循环在我的Java程序中工作?

+1

你解释了你得到的行为 - 它与你的期望有什么不同? – Blorgbeard

+0

更清楚发生什么事情与您预期发生的事情。正如所写,很难回答你的问题。 – nhouser9

回答

3

我想你忘记了重新指定number变量。之所以

但是,如果我再键入一个数字比10我得到同样的 消息更大。

请尝试下面的代码。感谢@ Dev.Joel的评论。我已经修改了循环到do-while以更好地适应这种情况。

import java.util.Scanner; 
import static java.lang.System.out; 

public class TestingStuf2 { 

    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 

      out.println("Enter a number"); 

      int number = keyboard.nextInt(); 

     do{ 
      if (number < 10) { 
       out.println("This number is too small."); 
       /* 
       * You should reassign number here 
       */ 
       number = keyboard.nextInt(); 
      }else{ 
       out.println("This number is big enough."); 
      }  
     }while(number < 10); 
     keyboard.close(); 
    } 

} 

我建议您使用break point来调试您的问题。以您的情况为例,您将2分配给number,并打印“此号码太小”。接下来,您使用keyboard.nextInt()让用户输入另一个int。但是,数字仍为2.因此,无论您此次输入什么内容,条件number < 10都成立,并且"This number is too small"将再次打印。

+1

如果你先输入一个更高的数字10永远不会输入while –

+0

@ Dev.Joel谢谢你的提醒。我将编辑答案。 – Gearon

相关问题