在输入有效之前,如何检查无效输入和循环? [英] How can I check for invalid input and loop until the input is valid?

查看:109
本文介绍了在输入有效之前,如何检查无效输入和循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从用户输入中找到列表中的最小数字。我需要询问用户列表中将包含多少个数字(并且只接受正数而不是字母),然后询问他们列表中的数字是什么(仅接受数字)。如何检查并保持循环直到数字有效?

I am trying to find the smallest number in the list from user input. I need to ask the user how many numbers are going to be in the list (and only accept positive numbers and no letters) and then ask them what the numbers are in the list (accepting only numbers). How can I check for this and keep looping until the numbers are valid?

public class SmallestInt {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {


        // Initialize a Scanner to read input from the command line
        Scanner input = new Scanner(System. in );
        int totalIntegers = 1;
        int num = 0;
        int smallest = 0;
        boolean inputValid = false;

        /* Prompt the user and validate their input to ensure they've entered a positive (greater than zero) integer. Discard/ignore any other data.
         */

        while (!inputValid)

        {
            System.out.print("How many integers shall we compare? (Enter a positive integer): ");

            try {
                totalIntegers = input.nextInt();
                inputValid = true;

            } catch (NumberFormatException e) {
                System.out.println("Invalid input!");
            }


            /* Read in the candidates for smallest integer
             * Validate this input as well, this time ensuring that the user has provided a valid int (any int will do at this point) and discarding any other data
             */
            for (int ii = 1; ii <= totalIntegers; ii++) {

                // Prompt 
                System.out.print("Enter value " + ii + ": ");

                num = input.nextInt();

                if (ii == 1) smallest = num;
                else if (num < smallest) smallest = num;

            }


            // display smallest int

            System.out.println("The smallest number entered was: " + smallest);
        }
    }
}


推荐答案

让我们为您提供示例,这样您就可以首先关注蓝图

Let's come up with an sample for you so you can follow as your blueprint

我选择了while while循环,因为你需要至少问一次这个问题。

first, I chose do while loop because you need to ask this question at least once.

do ... while循环的语法是:

do
{
   //Statements
}while(Boolean_expression);




请注意,布尔表达式出现在循环的末尾,所以
循环中的语句在测试布尔值之前执行一次。

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

如果布尔表达式为真,则控制流会跳回
要做,
并且循环中的语句再次执行。这个过程
重复,直到布尔表达式为假。

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

接下来,你需要看看如何在满足boolean_experssion时输入是正确的,所以你可以停止循环,或者如果它是错误的,你会不断提问。

Next, you need to see how you can staisfy the boolean_experssion when the input is right, so you can stop looping or if it is wrong, you keep asking the question.

我真正喜欢的方式是使用 sentinel值因为使用 break 关键字真的让我感到害怕。

The way that I really like is to use sentinel value because using break keyword really scares me.


在编程中,一个用于终止循环的特殊值。通常选择
sentinel值,以便不是循环将遇到并尝试执行的合法数据
值。对于
示例,在计算非负整数的循环算法中,
值-1可以设置为sentinel值,因为计算将
永远不会将该值视为合法处理输出。

In programming, a special value that is used to terminate a loop. The sentinel value typically is chosen so as to not be a legitimate data value that the loop will encounter and attempt to perform with. For example, in a loop algorithm that computes non-negative integers, the value "-1" can be set as the sentinel value as the computation will never encounter that value as a legitimate processing output.

因此当输入正确时你改变了i的值,所以你可以停止循环或其他方式,显示消息并一次又一次地询问问题,直到使用正确答案为止。

so when the input is right you change the value of i, so you can stop the looping or otherwise, showing the message and asking the question again and again till the use hits the right answer.

代码

    int i = 0;
    Scanner input = new Scanner(System.in);
    while (i == 0) {
        System.out.println("Enter number zero plz");
        int result = input.nextInt();
        if(result == 0 ){
            System.out.println("I entered right number");
            i = 1;
        } else
            System.out.println("you entered the wrong number \nplz try again");
    }

输出

这篇关于在输入有效之前,如何检查无效输入和循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆