[英]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.