【问题标题】:Why can I not enter the while loop? (Java)为什么我不能进入while循环? (爪哇)
【发布时间】:2022-10-16 06:27:15
【问题描述】:

我想提示用户在 while 循环中输入他们的值。该错误是由于尝试使用 input = kbd.nextInt() 接收用户的值,然后尝试在我的 while 循环中的条件中使用该对象名称(导致死锁)引起的。因此,当尝试运行它时,控制台是空白的。感谢您的帮助!

public static void main(String[] args) {
    

    Scanner keyboard = new Scanner(System.in);  
    
     
    int input = keyboard.nextInt(); 
    
    
    Random generator = new Random(); 
    int num = generator.nextInt(100);
            
    
    int counter = 10;
    
    
    while (input != num && counter > 0 )
    {
    
        System.out.print("Enter your guess at my number ");
        input = keyboard.nextInt(); 
        
        counter--; 
        
    }
        
    //close scanner 
    kbd.close();

}

}

【问题讨论】:

  • int input = kbd.nextInt(); int rNum = generator.nextInt(100)+1; int counter = 0; while (input != rNum && counter < 10 ) 1% 的机会进入循环。随机值为 1..100。如果输入错误的数字,则不满足循环条件,不会进入循环。

标签: java loops while-loop


【解决方案1】:

每当您使用接受输入的语句(在您的情况下 - int input = kbd.nextInt();)时,Java 应用程序都会在此处停止执行并等待来自指定源(此处为 System.in)的输入。尝试再次执行代码,这次输入一个随机数,这将是输入变量的值。之后循环将开始。 此外,在这种情况下,您应该将 int input = kbd.nextInt(); 更改为

int input = -1; 

这将消除随机数与循环(游戏)开始之前输入的数字相同的 1% 的机会。或者您可以设置一个 if 条件检查输入和随机数是否相等,以及它们是否采用新的随机数并再次检查(在循环中)。

【讨论】:

    【解决方案2】:

    在 while 循环之前使用语句 int input = kbd.nextInt();,您已经在等待用户输入 - 没有提示用户。我敢打赌,您的应用程序正在等待您输入第一个整​​数。由于您正在等待 while 循环开始并且应用程序正在等待您,因此存在死锁。

    弄清楚如何运行调试器来逐步执行您的代码。这将有很大帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-18
      • 2012-04-01
      • 2018-05-24
      • 1970-01-01
      • 2019-05-10
      • 2012-08-23
      • 2020-10-05
      • 2013-10-30
      相关资源
      最近更新 更多