简体   繁体   English

为什么在我的方法接受输入之前必须输入两次?

[英]Why do I have to enter in the input twice before my method accepts the input?

I'm making a simple mortgage calculator and trying to validate two things through two "if-statements" before moving on to the next method.我正在制作一个简单的抵押贷款计算器,并在继续使用下一个方法之前尝试通过两个“if 语句”验证两件事。 The first thing I'm checking is if the input from the scanner is an integer. If it is, I then want to check if the integer is between 1,000 and 1,000,000.我要检查的第一件事是扫描仪的输入是否为 integer。如果是,我想检查 integer 是否在 1,000 到 1,000,000 之间。

Below is the specific code:下面是具体代码:

public static Integer checkPrincipalValidation(Scanner scanner) {
        while (true) {
            if (scanner.hasNextInt()) {
                principal = parseInt(scanner.nextLine());
                if (principal >= 1_000 && principal <= 1_000_000) {
                    break;
                }
                    System.out.println(scanner.nextLine() + " is not between 1,000 and 1,000,000. Please enter correct Principal (1K - $1M):");
            }
            if (!scanner.hasNextInt()) {
                System.out.println(scanner.nextLine() + " is not a valid integer. Please enter correct Principal (Integer):");

            }
        }
        return principal;
    }

Below is the whole file if interested:如果有兴趣,下面是整个文件:


import java.util.Scanner;

import static java.lang.Float.parseFloat;
import static java.lang.Integer.parseInt;

public class Validation {
    static int principal;

    public static Integer checkPrincipalValidation(Scanner scanner) {
        while (true) {
            if (scanner.hasNextInt()) {
                principal = parseInt(scanner.nextLine());
                if (principal >= 1_000 && principal <= 1_000_000) {
                    break;
                }
                    System.out.println(scanner.nextLine() + " is not between 1,000 and 1,000,000. Please enter correct Principal (1K - $1M):");
            }
            if (!scanner.hasNextInt()) {
                System.out.println(scanner.nextLine() + " is not a valid integer. Please enter correct Principal (Integer):");

            }
        }
        return principal;
    }


    public static Float checkInterestValidation(Scanner scanner) {
        while (true) {
            if (scanner.hasNextFloat() || scanner.hasNextInt()) {
                if (scanner.hasNextInt()) {
                    return parseFloat(scanner.nextLine());
                }
                return scanner.nextFloat();
            } else {
                System.out.println(scanner.nextLine() + " is not a valid rate");
                System.out.print("Please enter correct Rate: ");
            }
        }

    }

    public static Integer checkPeriodValidation(Scanner scanner) {

        while (true) {
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                System.out.println(scanner.nextLine() + " is not a valid period");
                System.out.print("Please enter correct Period (Years): ");
            }
        }
    }


}

When it passes through the first "if-statement", I have to enter the number twice before it goes into the second "if-statement".当它通过第一个“if 语句”时,我必须在进入第二个“if 语句”之前输入两次数字。 Why?为什么? Thank you for your time.感谢您的时间。 I took a year off of coding so I'm extremely rusty and still extremely new to java, haha!我花了一年的时间写代码,所以我非常生疏,而且对 java 还是非常陌生,哈哈!

Every time you call scanner.nextLine() you must provide additional input.每次调用scanner.nextLine()时,您都必须提供额外的输入。

Let me write comments to your method to show you the points:让我对您的方法写评论以向您展示要点:

public static Integer checkPrincipalValidation(Scanner scanner) {
    while (true) {
        if (scanner.hasNextInt()) {  // (1)
            principal = parseInt(scanner.nextLine());  // (2)
            if (principal >= 1_000 && principal <= 1_000_000) {
                break;
            }
            //  (3) is the next line
            System.out.println(scanner.nextLine() + " is not between 1,000 and 1,000,000. Please enter correct Principal (1K - $1M):");
        }
        if (!scanner.hasNextInt()) {  // (4)
            //  (5) is the next line
            System.out.println(scanner.nextLine() + " is not a valid integer. Please enter correct Principal (Integer):");
        }
    }
    return principal;
}

On the code line marked (1) you check whether the input contains a valid integer value.在标记为 (1) 的代码行上,您检查输入是否包含有效的 integer 值。

If it is then at the code line (2) you read that value, parse it and store the value in principal .如果它在代码行 (2) 处读取该值,解析它并将该值存储在principal中。

Then, if the value for the principal is outside of the valid range, you read the next line of input at code line (3).然后,如果本金的值超出有效范围,则读取代码行 (3) 处的下一行输入。 This is not the same value as the one that you have read at code line (2) - that value was consumed and cannot be retrieved a second time!这与您在代码行 (2) 中读取的值不同 - 该值已被消耗且无法再次检索!

Then at code line (4) you check again if the next value from the input is a valid integer value.然后在代码行 (4) 处再次检查输入的下一个值是否为有效值 integer。 If there is no valid integer value, you consume that input at code line (5).如果没有有效的 integer 值,您将在代码行 (5) 处使用该输入。

The total effect is this:总的效果是这样的:

If the user enters for example a value "1" that value passes the condition on code line (1), is read from the input and parsed into an int value at code line (2).例如,如果用户输入值“1”,则该值通过代码行 (1) 中的条件,从输入中读取并在代码行 (2) 中解析为int值。

Since this value is not in the valid range of 1000 <= value <= 1_000_000 the code continues to line (3) where you require the user to input an additional line so that you can tell him that this new input is not between 1,000 and 1,000,000由于此值不在 1000 <= 值 <= 1_000_000 的有效范围内,代码继续到第 (3) 行,您需要用户输入额外的一行,以便您可以告诉他这个新输入不在 1,000 和1,000,000

Then the code progresses to code line (4), expecting an additional input.然后代码前进到代码行 (4),期待额外的输入。

To fix this mess you should rewrite your code maybe like this:要解决这个问题,您应该像这样重写代码:

public static int checkPrincipalValidation(Scanner scanner) {
    while (true) {
        if (scanner.hasNextInt()) {
            principal = scanner.nextInt();
            if (principal >= 1_000 && principal <= 1_000_000) {
                break;
            }
            System.out.println(principal + " is not between 1,000 and 1,000,000. Please enter correct Principal (1K - $1M):");
        } else {
            System.out.println(scanner.nextLine() + " is not a valid integer. Please enter correct Principal (Integer):");
        }
    }
    return principal;
}

Note that although this code solves your immediate problem, you might later on encounter additional problems when you read the following input with scanner.nextLine() - see the answer at Scanner is skipping nextLine() after using next() or nextFoo() for more information.请注意,虽然此代码解决了您眼前的问题,但您稍后可能会在使用 scanner.nextLine( scanner.nextLine()读取以下输入时遇到其他问题 - 请参阅Scanner is skipping nextLine() after using next() or nextFoo() for更多信息。

The gist of that question and answers: it is surprisingly difficult to use a Scanner if your input contains mixed input (single tokens like numbers or single words on the one hand and complete lines of input on the other hand).该问题和答案的要点:如果您的输入包含混合输入(一方面是数字或单个单词等单个标记,另一方面是完整的输入行),则使用Scanner非常困难。

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

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