[英]How to compare scanners input with an array?
I was wondering how I can compare the input from a scanner, to an array. 我想知道如何比较扫描仪和数组的输入。 Sorry if this is an easy question, but I'm fairly new to Java.
很抱歉,如果这是一个简单的问题,但我对Java很新。
Here's what I've written: 这是我写的:
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.
}
}
I want the user to only be able to input 1, 2, or 3. 我希望用户只能输入1,2或3。
Any help would be appreciated. 任何帮助,将不胜感激。
Thank you. 谢谢。
You can use this function: 你可以使用这个功能:
public static boolean isValidInput(int input, int[] acceptedInput) {
for (int val : acceptedInput) { //Iterate through the accepted inputs
if (input == val) {
return true;
}
}
return false;
}
Note that if you are working with strings, you should use this instead: 请注意,如果您正在使用字符串,则应使用此字符:
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;
}
You can use the binary search from Arrays class which will give you the index location of the given integer. 您可以使用Arrays类中的二进制搜索,它将为您提供给定整数的索引位置。
sample: 样品:
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.
}
If the result is negative then the answer
does not located in your array 如果结果为负,则
answer
不在您的数组中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.