2014-09-03 52 views
3

我在想如何将扫描仪的输入与数组进行比较。对不起,如果这是一个简单的问题,但我对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

任何帮助,将不胜感激。

谢谢。

+0

反过来想一想。元素组1,2,3是否包含您的输入? – 2014-09-03 23:36:54

+0

将它与'acceptedInput [i]'相比较,用于数组中的每个索引。 – Eran 2014-09-03 23:37:10

回答

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; 
} 
0

您可以使用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并不位于阵列中

+0

请注意,这需要对数组进行排序。 – immibis 2014-09-04 00:56:34

+0

@immibis他只有3件物品不需要排序。 – 2014-09-04 00:58:07