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

时间:2016-10-09 10:08:09

标签: java validation user-input do-while

我正在尝试验证用户输入,以便程序将循环回到询问用户等级的第一个问题,如果它不是int且int不在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);

3 个答案:

答案 0 :(得分:1)

为了使代码更清晰,您可以使用基于类和的封装 方法(封装是bOP的主要原因)。

因此,您尽可能将所有内容划分为较小的部分作为方法或类,然后每个方法只有一个简单的目的。这样整个程序就更容易阅读,理解和维护。

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

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;
}
}

答案 1 :(得分:0)

基本上我会读取System.in并且有些东西,首先我会尝试转换为Integer,然后检查Integer是否在正确的范围内:

package trial;

import java.util.Scanner;

public class TestScan {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            System.out.println("Please introduce a number:");
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()){
                String input=sc.next();
                Integer inputInt;
                try{
                    inputInt=Integer.parseInt(input);
                }catch(Exception e){
                    System.out.println("You must introduce a number");
                    continue;
                }
                if(inputInt<9 || inputInt>12){
                    System.out.println("Number must be between 9 and 12 (inclusive)");
                    continue;
                }
                System.out.println("Correct!");
            }
            sc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

值得注意的是,由于从System.in读取,该程序可以从IDE执行,因此您必须在IDE之外执行它:

1.-转到TestScan文件夹并编译它:javac TestScan.java

2.-在你的classpatch中指定这个类来执行它。例如。如果你在C:你可以使用像

这样的东西

C:&gt; java -classpath C:\ workspace \ StackOverflow \ src trial.TestScan

答案 2 :(得分:0)

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