简体   繁体   English

防止扫描程序读取Java中剩余的输入

[英]Preventing scanner from reading leftover input in Java

I am wondering how I can stop the scanner from reading extra erroneous input from the user. 我想知道如何阻止扫描仪读取用户的额外错误输入。

For example, I would like to read in the user input 2 one as 2 into the variable diam , which the program below achieves. 例如,我想将用户输入2 one作为2读入变量diam ,这是下面的程序实现的。

The issue is then, that the next loop automatically detects the one leftover from the input, and executes the if statement accordingly. 问题是,下一个循环自动检测到输入中剩下的one ,并相应地执行if语句。

I was able to work around this by creating two scanners, but unfortunately this is not allowed for this particular assignment. 我可以通过创建两个扫描仪来解决此问题,但是不幸的是,此特定任务不允许这样做。 In addition, we are required to use .hasNextInt() in our program. 另外,我们需要在程序中使用.hasNextInt()

How do I prevent this "spill-over" using only one scanner? 如何仅使用一台扫描仪防止这种“溢出”? I have to assume this question has been posed before, but I did not have much luck finding an answer. 我必须假设这个问题之前已经提出过,但是我没有太多运气找到答案。

    Scanner scnr = new Scanner(System.in);

    System.out.print("Enter the diameter of a "
            + "cylinder (in centimeters): ");
    // BEGIN: diameter input verification loop      
    for (;;) {
        if (!scnr.hasNextInt()) {
            System.out.print("Please enter an integer value "
                    + "(less than 2,147,483,648) as decimal digits: ");
            scnr.nextLine(); 
            continue;
        }
        diam = scnr.nextInt();
        if (diam >= 0) {
           //null statement
        } 
        else {
          System.out.print("Please enter a positive integer value: ");
          continue;
        }
    break;
    }
    //END: diameter input verification loop

    //prompts user for container height     
    System.out.print("Enter the height of a "
            + "cylinder (in centimeters): ");

    // BEGIN: height input verification loop        
    for (;;) {
        if (!scnr.hasNextInt()) {
            System.out.print("Please enter an integer value "
                    + "(less than 2,147,483,648) as decimal digits: ");
            scnr.nextLine(); 
            continue;
        }
        height = scnr.nextInt();
        if (height >= 0) {
           //null statement
        } 
        else {
          System.out.print("Please enter a positive integer value: ");
          continue;
        }
    break;
    }
    //END: height input verification loop`

One option would be to just read the entire line of input from the Scanner , and then retain only the first word. 一种选择是仅从Scanner读取整行输入,然后仅保留第一个单词。 For example, for the diameter of a cylinder you could use: 例如,对于圆柱体的直径,您可以使用:

System.out.print("Enter the diameter of a cylinder (in centimeters): ");
String input = scnr.nextLine();
try {
    int diam = Integer.parseInt(input.split(" ")[0]);
}
catch (NumberFormatException e) {
    System.out.print("Please enter an integer value "
                + "(less than 2,147,483,648) as decimal digits: ");
}

I can think of a couple of approaches: 我可以想到几种方法:

  • As Tim notes, you can use readLine() to read a complete line from the user, then parse the line. 正如Tim所指出的,您可以使用readLine()从用户那里读取完整的一行,然后解析该行。 You could use split , or create a new Scanner to parse the line, or various other approaches. 您可以使用split ,或创建新的Scanner来分析行,或使用其他各种方法。

  • You can stick with a single Scanner and call nextLine() to discard unconsumed characters up to and including the next end-of-line. 您可以使用单个Scanner并调用nextLine()来丢弃直到下一行(包括下一行nextLine()未使用字符。 Obviously, you need to do this after calling nextInt() . 显然,您需要调用nextInt() 之后执行此操作。 For example: 例如:

     height = -1; while (height < 0) { if (!scnr.hasNextInt()) { System.out.print("Please enter an integer value " + "(less than 2,147,483,648) as decimal digits: "); } else { height = scnr.nextInt(); if (height < 0) { System.out.print("Please enter a positive integer value: "); } } scanner.nextLine(); } 

    (The above version of your code has restructured things to get rid of the break and continue . The restructuring also allows me to put the readLine as an unconditional last statement for the loop. I think it makes the logic easier to understand ...) (以上版本的代码对内容进行了重组,以摆脱breakcontinue 。重组还使我可以将readLine作为循环的无条件最后一条语句。我认为它使逻辑更易于理解...)

// BEGIN: height input verification loop
        for (;;) {

            scnr.nextLine(); /* read fresh input, deleting the left over input */

            if (!scnr.hasNextInt()) {
                System.out.print("Please enter an integer value " + "(less than 2,147,483,648) as decimal digits: ");
                scnr.nextLine();
                continue;
            }
            height = scnr.nextInt();
            if (height >= 0) {
                // null statement
            } else {
                System.out.print("Please enter a positive integer value: ");
                continue;
            }
            break;
        }

You can simply add a scnr.nextLine() to remove the "old" scnr left over from the previous input. 您只需添加scnr.nextLine()即可删除上一个输入中遗留的“旧” scnr This fixes the spill-over problem. 这解决了溢出问题。

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

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