lundi 26 septembre 2022

Random integers, Array, Linear search

The program is about creating random values and doing linear search. The results shown when run is the "the input value" is not in the list, though it is present in the generated random list Thank you so much.

import java.util.Random;
import java.util.Scanner;
import java.util.HashSet;
import java.util.Set;


public class LinearSearch {

    public static void main(String[] args) {
                    
        int array [] = new int [100];
        
        Random ValGener = new Random ();
        Set set = new HashSet <Integer>();
        
        for (int i = 1; i <= array.length; i++) {
            int randomNumber = ValGener.nextInt(100);
            
            if (!set.contains(randomNumber)){
                    set.add(randomNumber);
                    
            System.out.println(i + " Random No: " + randomNumber);
                }else i--;
            
             }
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the random searched value");

            int value = input.nextInt();
    
            for (int index = 0; index < array.length; index++){

                if (array [index] == value){

                       System.out.println(value+ " is found at Index "+(index+1));
                       }
           
                else; {

                       System.out.println(value+ " is not in the list");
                      break;
                       }
     
                    }
                
}   

}



Aucun commentaire:

Enregistrer un commentaire