【发布时间】:2014-11-08 20:34:19
【问题描述】:
我正在通过命令行创建一个用户界面,该界面将询问从 1 到 4 的选项,并且我想要进行错误检查。只允许 1 - 4 之间的整数。这是我到目前为止的代码。我希望该方法将 userInput 整数返回给另一个可以用它做一些事情的方法。
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新手,所以任何东西都有帮助。谢谢!
【问题讨论】:
标签: java variables scope try-catch console-application