我正在通過命令行創建一個用戶界面,該用戶界面將要求從1到4的選項,並且我想要進行錯誤檢查。只允許1到4之間的整數。這是迄今爲止的代碼。我想方法返回userInput整數到另一個方法,它會做一些東西。try catch塊中的變量範圍
package contactmanager;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author andyjohnson
*/
public class UserInterface {
public static Integer GetInput() {
Scanner in = new Scanner(System.in);
//Integer userInput;
System.out.println("Welcome to the contact manager\nMake a selection below:");
System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
try {
Integer userInput = in.nextInt();
if (userInput < 1 || userInput > 4) {
System.out.println("Please enter a valid selection");
UserInterface.GetInput();
}
} catch (InputMismatchException e) {
e.getMessage();
System.out.println("Please enter a valid selection");
UserInterface.GetInput();
}
return userInput;
}
}
我的return語句在IDE中被加下劃線,並告訴我它沒有被初始化。我想全局初始化它,但允許try語句改變它的值。我試過this.userInput = userInput,但我無法弄清楚我的範圍被破壞了。我如何給try塊的全局範圍?我是新來的Java,所以任何東西都有幫助。謝謝!
我需要爲每個規範再次調用UserInterface.GetInput()。如果輸入驗證失敗,程序需要重新輸入菜單。我試過這個建議,但它似乎沒有驗證輸入的整數,如果它是0或5.輸入像foo這樣的字符串給了我在catch語句中的代碼。如果嘗試失敗驗證或者catch執行什麼是再次調用該菜單方法的最佳方式?規範說這應該給用戶輸入驗證失敗後的菜單。我想讓UserInterface方法是靜態的,所以它不需要實例化。 – 2014-11-08 21:06:02
我不知道你正在查看的'規範'中列出了什麼條件。我測試了這個方法,它似乎適用於我。我不明白'UserInterface.GetInput()'如何綁定到它,因爲你已經得到了輸入。 – 2014-11-08 21:15:29
爲了清楚起見,我在原始答案中添加了評論。 – 2014-11-08 21:18:57