作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想知道如何将扫描仪的输入与数组进行比较。很抱歉,如果这是一个简单的问题,但我对 Java 还很陌生。
这是我写的:
public static void handleProjectSelection() {
Scanner getProjectNum = new Scanner(System.in);
int answer;
int[] acceptedInput = {1, 2, 3};//The only integers that are allowed to be entered by the user.
System.out.println("Hello! Welcome to the program! Please choose which project" +
"you wish to execute\nusing keys 1, 2, or 3.");
answer = getProjectNum.nextInt(); //get input from user, and save to integer, answer.
if(answer != acceptedInput[]) {
System.out.println("Sorry, that project doesn't exist! Please try again!");
handleProjectSelection();//null selection, send him back, to try again.
}
}
我希望用户只能输入 1、2 或 3。
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
你可以使用这个函数:
public static boolean isValidInput(int input, int[] acceptedInput) {
for (int val : acceptedInput) { //Iterate through the accepted inputs
if (input == val) {
return true;
}
}
return false;
}
请注意,如果您使用的是字符串,则应改用它:
public static boolean isValidInput(String input, String[] acceptedInput) {
for (String val : acceptedInput) { //Iterate through the accepted inputs
if (val.equals(input)) {
return true;
}
}
return false;
}
关于java - 如何将扫描仪输入与数组进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655199/
我是一名优秀的程序员,十分优秀!