Java 如何将扫描仪输入与数组进行比较?
我想知道如何将扫描仪的输入与阵列进行比较。如果这是一个简单的问题,很抱歉,但我对Java还是相当陌生的 以下是我写的:Java 如何将扫描仪输入与数组进行比较?,java,Java,我想知道如何将扫描仪的输入与阵列进行比较。如果这是一个简单的问题,很抱歉,但我对Java还是相当陌生的 以下是我写的: public static void handleProjectSelection() { Scanner getProjectNum = new Scanner(System.in); int answer; int[] acceptedInput = {1, 2, 3};//The only integers that are allowe
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
任何帮助都将不胜感激
谢谢。您可以使用“从数组进行二进制搜索”类,该类将为您提供给定整数的索引位置 示例:
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(Arrays.binarySearch(acceptedInput,answer)<0){
System.out.println(“抱歉,该项目不存在!请重试!”);
handleProjectSelection();//空选择,将其发送回,然后重试。
}
如果结果为阴性,则回答不在数组中您可以使用此功能:
公共静态布尔值isValidInput(int输入,int[]接受输入){
对于(int-val:acceptedInput){//遍历接受的输入
如果(输入==val){
返回true;
}
}
返回false;
}
请注意,如果您使用的是字符串,则应改为使用:
公共静态布尔值isValidInput(字符串输入,字符串[]接受输入){
for(String val:acceptedInput){//遍历接受的输入
如果(值等于(输入)){
返回true;
}
}
返回false;
}
反向思考。元素组1、2、3是否包含您的输入?请将其与数组中每个索引的acceptedInput[i]
进行比较。注意,这需要对数组进行排序。@immibis他只有3项,不需要对其进行排序。