如何在程序得到有效答案之前提示用户,怎么做N次?

How to prompt user until the program gets a valid answer, how to do it N times?

我正在尝试制作一个简单的程序,如果用户在数组中输入一个数字,则该数组数字等于的数字将会出现。它工作完美,除非用户输入一个不在数组中的数字,然后在数组中输入一个数字。发生的事情是程序没有在正确的地方显示答案。

Scanner ethan = new Scanner(System.in);

System.out.println("Enter array place: ");
int amount = ethan.nextInt();

int array[] = {2, 4, 9};

for(int i = 0; i<amount; i++)
{
    if (amount == 0) {
        System.out.println(array[0]);
    } else if (amount == 1) {
        System.out.println(array[1]);
    } else if (amount == 2) {
        System.out.println(array[2]);
    } else {
        System.out.println("Enter integer in array:");
        amount = ethan.nextInt();
    }
}

您不应在 for 循环中使用输入的数字

for(int i = 0; i < amount; i++){

如果我输入0呢?该程序不会 运行 一个循环。

试试这个,应该有效。我在代码中为您做了一些评论。

int array[] = {2, 4, 9};
Scanner ethan = new Scanner(System.in);

/**
 * This gets one valid number from the user
 */
public void getOneNumber() {
    /**
     * This is our "switch" variable
     */
    boolean validIndexGiven = false;

    while (!validIndexGiven)

    {
        /** This is actually called "array index"*/
        System.out.println("Enter array index: 0 to " + (array.length - 1));
        int index = ethan.nextInt();

        /** Here we check if given integer is in the bounds of array.
         * No need to check every possible value.
         * What if we had array[100]? */
        if (index >= 0 && index < array.length) {
            /** Amount was a valid number. */
            System.out.println(array[index]);
            /** Toggling the switch */
            validIndexGiven = true;
        }
    }
}

/**
 * This prompts the user for numbers as many times as there are elements in array
 */
public void getManyNumbers() {
    int length = array.length;
    for (int i = 0; i < length; i++) {
        getOneNumber();
    }
}

您似乎希望用户输入数字的次数与数组中的数字一样多(在本例中为 3 次)。但是,似乎您只让用户输入它,无论他们在开头输入多少次(当它说 "Enter array place: " 时)。为什么不尝试 i<array.length 而不是 i<amount?或者,您可以使用 while 循环,并且只在用户输入有效数字时递增 i

提示:你可以说if ((amount >= 0) && (amount <= 2)) System.out.println(array[amount]);

我明白了。代码如下(也谢谢大家留下的答案):

    Scanner ethan = new Scanner(System.in);

    System.out.println("Enter array place: ");
    int amount = ethan.nextInt();

    int array[] = { 2, 4, 9 };

    while(true){
        if (amount == 0) {
            System.out.println(array[0]);
        break;
        } else if (amount == 1) {
            System.out.println(array[1]);
        break;
        } else if (amount == 2) {
            System.out.println(array[2]);
        break;
        } else {
            System.out.println("Enter integer in array:");
            amount = ethan.nextInt();
        }

    }

}
}