lundi 29 août 2016

Search an Array for a user input

I am trying to finish an assignment. I have to write a program in Java that generates random numbers in an array size100 and then asks the user for a number between 1 and 100. If the number is in the array it displays that the number was found at what location. If not it kicks back that no number was found. So far I can only get it to kick back that the number was not found. It prints it back out 4 different times.

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");
            }
        }
    }


}




Aucun commentaire:

Enregistrer un commentaire