[英]How to compare scanners input with an array?
我想知道如何比较扫描仪和数组的输入。 很抱歉,如果这是一个简单的问题,但我对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;
}
您可以使用Arrays类中的二进制搜索,它将为您提供给定整数的索引位置。
样品:
if(Arrays.binarySearch(acceptedInput , answer ) < 0) {
System.out.println("Sorry, that project doesn't exist! Please try again!");
handleProjectSelection();//null selection, send him back, to try again.
}
如果结果为负,则answer
不在您的数组中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.