循环以在数组中选取数字时不断询问猜测 (java)



我正在编写代码以生成一个介于 1 和 100 之间的 100 个随机数数组。然后,我想向用户询问一个数字,然后在数组中搜索该数字。如果该号码存在,我想将其从数组中删除并要求用户提供另一个号码。我想重复此操作,直到用户猜到为止错误。如果用户猜错了,我想以相反的顺序输出剩余的数组内容。

我想我写得正确,但这是我的问题;我无法弄清楚如何让程序不断询问猜测是否正确。

这是我的代码,我知道它只是一个需要的良好放置的 for 循环,我只是看不到在哪里。我真的很感激在这方面的一些帮助。谢谢!我不是在寻找有人给我只需要一个转向的代码。

int[] randomArray = new int[10];
    // For loop to fill the array with random elements from 1 to 100
    for (int i = 0; i < randomArray.length; i++) {
        randomArray[i] = (int) (Math.random() * 100);
        // Print the array
        System.out.print(randomArray[i] + ", ");
    }
    // Print a blank line
    System.out.println();
Scanner input = new Scanner(System.in);
    // Declare an int variable to hold the number
    int searchNumber;
    // Ask the user to enter a number
    System.out.println("Please enter a number to search for between 1 and 
100: ");
    // Initialise the int variable with the number entered
    searchNumber = input.nextInt();
    // initialise boolean as false
    boolean found = false;
    // for loop to search the array for the value entered by the user
    for (int i = 0; i < randomArray.length; i++) {
        if (searchNumber == randomArray[i]) {
            // If found then set boolean to true
            found = true;
            // If found print out the index where it was found and inform 
the user that it
            // will be removed from the array
            System.out.println("Your number was found at index " + i + " 
and will be deleted from the array:");
            // create a new array which is one element shorter than the 
original
            int[] result = new int[randomArray.length - 1];
            // Copy the the new array from the original array
            System.arraycopy(randomArray, 0, result, 0, i); // i is the 
element to be removed
            System.arraycopy(randomArray, i + 1, result, i, result.length - 
i);
            // Print the new array without the element i
            System.out.println(Arrays.toString(result));
        }
    }
    // code to inform the user if their value was not found and print the 
array in
    // reverse
    if (!found) {
        // Print text telling the user that the number was found and the 
array will be
        // printed in reverse
        System.out.println("Your number was not found, here is the array in 
reverse");
        // For loop to print the array in reverse
        for (int k = randomArray.length - 1; k >= 0; k--)
            System.out.print(randomArray[k] + ", ");
    }
}

问题;我无法弄清楚如何让程序继续询问猜测是否正确。?

然后,您应该围绕一些 do while 循环构建逻辑。

//Initialize random values here.
do{
     //Get input & process.
     //Do all Logics.
}while( exit condition based on your logic else process input again )

这应该可以做到。我希望。

最新更新