java - 有没有办法让这个用户验证代码更高效和/或更容易阅读?

标签 java validation user-input do-while

我正在尝试验证用户输入,以便程序将循环回到询问用户成绩的第一个问题,如果它不是 int 并且 int 不在 9 - 12 的范围内(包括 9 和 12) 。有没有“更好”的方式来编写这段代码?

do
    {
        if (userGrade < 9 || userGrade > 12)
        {
            System.out.println("That is not a valid grade!");
        }

            System.out.printf("Grade (9-12): ");

        while(!enterInfo.hasNextInt())
        {
            System.out.println("That is not a number! Enter in a valid number.");
            enterInfo.next();
        }
        userGrade = enterInfo.nextInt();
    } while (userGrade < 9 || userGrade > 12);

最佳答案

为了使代码更简洁,您可以使用基于类的封装, 方法(顺便说一句,封装是 OOP 的主要原因)。

所以你尽可能将所有内容分成更小的部分,如方法或类,那么每个方法只有一个简单的目的。这样整个程序就更容易阅读、理解和维护。

请注意例如扫描仪对象如何在 readInput 方法的本地上下文中使用。

import java.util.InputMismatchException;
import java.util.Scanner;

public class KillerLoop {

private boolean notReady;
private int grade;

public static void main(String[] args) {

    new KillerLoop();

}

/**
 * the default constructor calls the doStuff method
 * which contains the main loop of the program
 */
public KillerLoop() {
    this.notReady = true;
    doStuff();
}

/**
 * the programs main loop
 */
private void doStuff() {
    while (this.notReady) {
        int input = this.readInput();
        this.verifyInput(input);
    }
    System.out.println("Grade " + this.grade + " is a correct grade!");
}

/**
 * verifies a users input
 * if the input is correct, notReady will be set
 * to false so that the programs main loop is left
 * (you could also use an if construct with break for this purpose)
 * @param userGrade the users input
 */
private void verifyInput(int userGrade) {
    if (userGrade < 9 || userGrade > 12) {
        System.out.println("That is not a valid grade!\n" + "Grade (9-12): ");
    } else {
        this.grade = userGrade;
        this.notReady = false;
    }

}

/**
 * this method reads input from the command line
 * and returns an integer if successful
 * @return the users input as integer
 */
private int readInput() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("enter a grade");

    int userGrade = 0;

    try {
        userGrade = scanner.nextInt();
    } catch (InputMismatchException e) {
        System.out.println("That is not a number! Enter in a valid number.");
        this.readInput(); //this recursion might not always be a good idea ;)
    }
    return userGrade;
}
}

关于java - 有没有办法让这个用户验证代码更高效和/或更容易阅读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942346/

相关文章:

java - 在 Java 中执行日期和时间计算

java - 每次输入/输出后是否需要重新创建 DataInputStream 或 DataOutputStream

java - http获取android异步任务

javascript - 使用范围数据进行 Angular ng-pattern 正则表达式验证

java - 线程中的 MouseMotionListener

java - 如何检查用户输入而不退出错误

javascript - 如何编写正则表达式来验证特殊位置的字符?

java - 在java中将递归帕斯卡三角形居中?

java - 如何从另一种方法访问用户输入

javascript - 防止 Web 应用程序中页面之间的击键丢失