簡體   English   中英

有沒有辦法讓這個用戶驗證代碼更有效和/或更容易閱讀?

[英]Is there a way to make this user validation code more efficient and/or easier to read?

我正在嘗試驗證用戶輸入,以便程序將循環回到第一個問題,如果它不是 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);

為了使代碼更清晰,您可以使用基於類和方法的封裝(封裝是 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;
}
}

基本上我會閱讀 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.- 在你的類補丁中指定這個類來執行它。 例如,如果你在 C 中:你可以使用類似的東西

C:>java -classpath C:\\workspace\\StackOverflow\\src trial.TestScan

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM