[英]Java Input Validation Design
這里是新手,請放輕松...
清除下面的輸入驗證邏輯的 Java/OOP 方法是什么? 在整個main
方法中多次執行檢查以確保已輸入int
。 多次復制輸入驗證行感覺很臟。 注意每個輸入的問題變化。
我假設一種解決方案是將keyInput
和問題(字符串)傳遞給完成驗證並在輸入正確時返回keyInput.nextInt
的方法。
非新手會做什么?
謝謝你。
public static void main(String[] args) {
Scanner keyInput = new Scanner(System.in);
int level = 0;
boolean badInput = true;
int answer = 0;
while (badInput) {
System.out.print("Enter a level between 1 and 4: ");
if (!keyInput.hasNextInt()) {
System.out.println("*** Input is not an integer! ***\n");
keyInput.next();
continue;
}
level = keyInput.nextInt();
if (level < 1 || level > 5) {
System.out.println("*** Number is not between 1 and 4! ***\n");
continue;
}
badInput = false;
}
MathChallenge game = new MathChallenge(level);
badInput = true;
while (badInput) {
System.out.print("Enter the sum of " + game.getArray() + ": ");
if (!keyInput.hasNextInt()) {
System.out.println("*** Input is not an integer! ***\n");
keyInput.next();
continue;
}
...
創建一個包含重復代碼的方法,並將任何變量片段作為 arguments 傳遞給該方法。
例如:
public int getNumber(Scanner keyInput, String prompt, int min, int max) {
while (true) {
System.out.print(prompt);
if (!keyInput.hasNextInt()) {
System.out.println("*** Input is not an integer! ***\n");
keyInput.next();
continue;
}
number = keyInput.nextInt();
if (number < min || number > max) {
System.out.println("*** Number is not between " + min + " and " + max + "! ***\n");
continue;
}
return number;
}
}
然后這樣稱呼它:
public static void main(String[] args) {
Scanner keyInput = new Scanner(System.in);
int level = getNumber(keyInput, "Enter a level between 1 and 4:", 1, 4);
MathChallenge game = new MathChallenge(level);
int sum = getNumber(keyInput, ""Enter the sum of " + game.getArray() + ": ", 0, 100);
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.