lundi 27 juillet 2020

Using for loop to find an element that appears multiple times in a random, unsorted array

My goal is to print out a user input value (and its corresponding index) if it appears 1 or more times in a random generated array of 50 integers. If I search the array for a value, and it happens to appear more than once, however, only one location of the element is printed, and then the if-else statement is executed. If I remove the break at the end of the third for loop, the whole thing falls apart. I've attached an image but here is the part of it that is giving me an issue. Apologies if the code is not clean, I'm very new.

public static void main(String[] args) {

    System.out.println("IDS201 HW3:\n");
    System.out.println("1. Generate 50 random integer unsorted list.\n");
    
    Scanner stdin = new Scanner(System.in);
    
    int[] randomNumbers = new int[50];
    for(int index = 0; index < randomNumbers.length; index++) {
        randomNumbers[index] = (int) (Math.random()*100);
    }//end for

    int count = 0;
    for(int i = 0; i < randomNumbers.length; i++) {
        System.out.print(randomNumbers[i] + ",");
        count++;
        if(count == 10) {
            System.out.println();
            count = 0;
            }
        }//end for
    
    System.out.println("\nSearch value?");
    int x = stdin.nextInt();
    int i;
    for(i = 0; i < randomNumbers.length; i++) {
        if(randomNumbers[i] == x) 
            break;}
            
    if (i != randomNumbers.length) {
        System.out.println("\nFound " + x + " in array [" + i + "]");}
    else {
        System.out.println(x + " is not in the list");}
    
    {int temp;
    int size = randomNumbers.length;

    for(i = 0; i<size; i++ ){
       for(int j = i+1; j<size; j++){
          if(randomNumbers[i]>randomNumbers[j]){
             temp = randomNumbers[i];
             randomNumbers[i] = randomNumbers[j];
             randomNumbers[j] = temp;
          }
       }
    }
    System.out.println("\nSmallest element of the array is: " + randomNumbers[0]);}
    System.out.println("\n3. Sort the list:");
     int size = randomNumbers.length;
     for(i=0; i<size; i++)  
       {  
           for(int j=i+1; j<size; j++)  
           {  
               if(randomNumbers[i] > randomNumbers[j])  
               {  
                   int temp = randomNumbers[i];  
                   randomNumbers[i] = randomNumbers[j];  
                   randomNumbers[j] = temp;  
               }  
           }  
       }  

     System.out.print("Now the Array after Sorting is :\n\n"); 
       int count1 = 0;
       for(i=0; i<size; i++)  
       {  
           System.out.print(randomNumbers[i]+ ",");
           count++;
           if(count == 10) {
               System.out.println();
               count = 0;
         }
     }  
}       

}

if statement in for loop

Aucun commentaire:

Enregistrer un commentaire