在Array中搜索用户输入

时间:2016-08-29 17:36:56

标签: java arrays eclipse search random

我正在努力完成作业。我必须用Java编写一个程序,它在数组size100中生成随机数,然后向用户询问1到100之间的数字。如果数字在数组中,则显示该数字在哪个位置找到。如果没有,它会踢回来没有找到任何数字。到目前为止,我只能让它回过头来找不到号码。它会将它打印出来4次。

package lab1;

import java.util.Random; import java.util.Scanner;

public class RandomArray {
public static void main(String[] args) {
    int [] randomArray = new int [100];
    Random randomGenerator = new Random();

for (int i = 0; i< randomArray.length; i++){
    randomArray[i] = randomGenerator.nextInt(100);

}
Scanner input = new Scanner (System.in);
int searchNumber;
System.out.println("Please enter a number to search for between 1 and 100: ");
searchNumber= input.nextInt();



        boolean found = false;
        for (int i = 0; i < randomArray.length; i++){
            if (searchNumber == randomArray[i]){
                found = true;
                break;

            }

        if (found){
            System.out.println("We have found your" + "number at index " + i);
        }else{
                System.out.println("We did not find your number");
            }
        }
    }


}

2 个答案:

答案 0 :(得分:0)

-s循环中的if语句。因此,每次forsearchNumber == randomArray[i] if {found} false you check&#34;我们没有找到您的号码&#34;`。

PS:了解如何使用调试器。它大大简化了你的生活。

答案 1 :(得分:0)

你忘了这种情况,如果有两个以上相同数字的位置,因为它只是生成随机数。 怎么样:

boolean found = false;
    for (int i=0; i < randomArray.length; i++) {
        if (searchNumber == randomArray[i]) {
            found = true;
            System.out.println("We have found your number at index " + i);
        }
    }

    if (!found) {
       System.out.println("We did not find your number");
    }