简体   繁体   English

尽管终止表达式,循环也不会结束

[英]Loop will not end despite the terminating expression

Hello Stack overflow community, 你好堆栈溢出社区,

My prompt is: **" You will do error checking to make sure that the hour entered is in the range [0, 23]. Keep asking the user until the user enters a time within the valid range. 我的提示是:**“您将进行错误检查,以确保输入的小时数在[0,23]范围内。不断询问用户,直到用户输入的时间在有效范围内。

My program when it has the correct integer inputs (any int input really) will work correctly. 当我的程序具有正确的整数输入(实际上是任何int输入)时,它将正常工作。 However, if i enter a non-int, then everything is stuck in an infinite loop. 但是,如果我输入非整数,则所有内容都会陷入无限循环。

What am I doing wrong? 我究竟做错了什么?

   import java.util.*;
public class Tester2 {
    int a; // any valid int number

public void loop() 
{
    Scanner sc = new Scanner(System.in);
    int x=0; // terminating int
    while(x==0) 
    {
        System.out.println("Enter 0-23: ");


            try
            {
                if(sc.hasNextInt()) 
                {
                    a=sc.nextInt();
                    if((a>=0&&a<=23)) 
                    {
                        System.out.println("Success! ");
                        x=1;
                    }
                    else 
                    {
                        System.out.println("Retry! ");
                        a=0;
                        x=0;
                    }
                }
            }
            catch (NumberFormatException ex) 
            {
                System.out.println("invalid input");
            }

        }

}

}

sc.hasNextInt() will return false if the next element to be read is not a valid integer. 如果下一个要读取的元素不是有效的整数,则sc.hasNextInt()将返回false However, this element is not read at any point in your code in that case. 但是,在这种情况下,代码中的任何时候都不会读取此元素。

You should ensure that this element is read and discarded when sc.hasNextInt() is false (adding sc.next() inside an else block should do the trick). 您应该确保在sc.hasNextInt()为false时读取并丢弃此元素sc.next()else块中添加sc.hasNextInt()应该可以解决问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM