简体   繁体   English

使用嵌套While循环确保类型安全输入

[英]Ensuring Type-Safe Input Using Nested While-loops

The program that I have written below was designed so that if a user doesn't enter an integer when prompted, the program will loop until they do. 我在下面编写的程序经过精心设计,以便如果用户在出现提示时未输入整数,则该程序将一直循环直到他们输入。 This works for the initial check, but the second check does not work. 这适用于初始检查,但第二次检查不起作用。 The code is as follows: 代码如下:

import java.util.Scanner;
public class SafeInput
{
    public static void main(String[]args)
    {
        System.out.println("Please enter any integer. If you want to exit, enter -1>");
        Scanner scan = new Scanner(System.in);

        while(!scan.hasNextInt())
        {
            String garbage = scan.nextLine();
            System.out.println("You've entered garbage.");
        }

        int input = scan.nextInt();

        while(input != -1)
        {           
            System.out.println("\nYou entered: "+input);
            System.out.println("Please enter any integer. If you want to exit, enter -1>");

            while(!scan.hasNextInt())
            {
                System.out.println("You've entered garbage.");
                String garbage1 = scan.nextLine();
            }

            input = scan.nextInt();
        }

        System.out.println("-1 entered. Goodbye");
    }
}

Here's what happens when I execute the program: 当我执行程序时,将发生以下情况:

Please enter any integer. If you want to exit, enter -1>
this is a string
You've entered garbage.
1

You entered: 1
Please enter any integer. If you want to exit, enter -1>
2

You entered: 2
Please enter any integer. If you want to exit, enter -1>
this is also a string
You've entered garbage.
You've entered garbage.
string
You've entered garbage.
1

You entered: 1
Please enter any integer. If you want to exit, enter -1>
2

You entered: 2
Please enter any integer. If you want to exit, enter -1>
-1
-1 entered. Goodbye

Why is it that when I fail the second check for an integer, the program outputs: 为什么在第二次检查整数失败时,程序输出:

You've entered garbage.
You've entered garbage.

Instead of: 代替:

You've entered garbage.

Thanks! 谢谢!

second while loop should be updated like below. 第二个while循环应如下更新。

        while(input != -1)
        {           
            System.out.println("\nYou entered: "+input);
            System.out.println("Please enter any integer. If you want to exit, enter -1>");
            scan.nextLine();
            while(!scan.hasNextInt())
            {
                System.out.println("You've entered garbage");
                String garbage1 = scan.nextLine();
            }

            input = scan.nextInt();
        }

use next() instead of nextLine(). 使用next()代替nextLine()。

     while(input != -1) {           
                System.out.println("\nYou entered: "+input);
                System.out.println("Please enter any integer. If you want to exit, enter -1>");

                while(!scan.hasNextInt())
                {
                    System.out.println("You've entered garbage.");
                    String garbage1 = scan.next();
                }

                input = scan.nextInt();
}

Look at Scanner#nextLine() java doc, 看一下Scanner#nextLine()Java文档,

This method returns the rest of the current line, excluding any line separator at the end. 此方法返回当前行的其余部分,但不包括最后的任何行分隔符。 The position is set to the beginning of the next line. 该位置设置为下一行的开始。

See code 见代码

Debug: 调试:

while(input != -1)
    {           
        System.out.println("\nYou entered: "+input);
        System.out.println("Please enter any integer. If you want to exit, enter -1>");

        while(!scan.hasNextInt())
        {
            System.out.println("-- Second -- ");
            System.out.println("You've entered garbage.");
            String garbage1 = scan.nextLine();
            System.out.println(" garbage1 -> " + garbage1);
        }

        input = scan.nextInt();
    }

Output: 输出:

Please enter any integer. If you want to exit, enter -1>
q
-- First -- 
You've entered garbage.
1
 -- input --1

You entered: 1
Please enter any integer. If you want to exit, enter -1>
aa
-- Second -- 
You've entered garbage.
 garbage1 -> 
-- Second -- 
You've entered garbage.
 garbage1 -> aa
ab
-- Second -- 
You've entered garbage.
 garbage1 -> ab

Just for fun I did some 'enhanced' implementation. 只是为了好玩,我做了一些“增强”的实现。 It should work correctly. 它应该可以正常工作。

package example;

    import java.util.Scanner;

    public class SafeInput {

        public static void main(String[] args) {
            System.out.println("Please enter any integer. If you want to exit, enter -1>");
            try (Scanner scan = new Scanner(System.in)) {
                while (true) {
                    int input = 0;
                    String garbageOutput = null;
                    if (scan.hasNextInt() && ((input = scan.nextInt()) != -1)) {
                        System.out.println("\nYou entered: " + input);
                        System.out.println("Please enter any integer. If you want to exit, enter -1>");
                    } else if (scan.hasNextInt() && ((input = scan.nextInt()) == -1)) {
                        System.out.println("-1 entered. Goodbye");
                        break;
                    } else if (!scan.hasNextInt() && (scan.hasNextLine())
                            && (!(garbageOutput = scan.nextLine()).isEmpty())) {
                        System.out.println(String.format("You've entered garbage - [%s]", garbageOutput));
                    }
                }

            }

        }

    }

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

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