gpt4 book ai didi

java - 如何将扫描仪输入与数组进行比较?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:58 26 4
gpt4 key购买 nike

我想知道如何将扫描仪的输入与数组进行比较。很抱歉,如果这是一个简单的问题,但我对 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;
}

关于java - 如何将扫描仪输入与数组进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com