How to find the random index in an array?

–7 votes
asked Sep 13, 2017 by dhanesh-r
  1. Create 8 randomly generated integer values between 1 to 50. DONE
  2. Display the series of values on screen. DONE
  3. Users has to enter value. Find index & display.
  4. if value cannot be found, display -none.

1 Answer

0 votes
answered Sep 20, 2017 by tobias-geiselmann

This is pretty easy. As you already completed step 1 and 2 you just have to ask the user for an input, search your array and output the index, if the input matches a value in the array.

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    Random random = new Random(); 
    int[] numbers = new int[8];

    for(int i = 0; i < 8; i++) {
        numbers[i] = random.nextInt(50) + 1;
        System.out.print(numbers[i] + ", ");
    }

    System.out.print("\nInput value: ");
    int input = scanner.nextInt();
    boolean found = false;

    for(int i = 0; i < numbers.length; i++) {
        if(input == numbers[i]) {
            System.out.println("Index: " + i);
            found = true;
        }
    }

    if(!found) {
        System.out.println("none");
    }
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...