mercredi 15 février 2023

I need to find the top 5 numbers in a 2D array of random numbers

I am pretty new to java and am just learning 2D arrays. I need to get the top 5 numbers and have tried everything I could think of. I was able to get the highest number using an If statement but am not able to get past that. I figured that I would try and get the second number and then move on to the rest. My friend said he got it done using for loops but I also could not get that to work. Any help would be appreciated. Thanks!

This is the code that I used:

package secondAssignment;

import java.util.Random;

public class BiggestNumbersRectangular {

    public static void main(String[] args) {

        Random rand = new Random();

        int[][] arrSize = new int [4][5];
        
        
        for (int i = 0; i < arrSize.length; i++) {
            for (int j=0; j< arrSize.length; j++) {
                arrSize[i][j] = rand.nextInt(89) + 10;
                
                System.out.print(arrSize[i][j] + " ");
            }
                
            System.out.println();
            
        }
        
        int max = arrSize [0][0];
        int largeNumTwo = arrSize [0][0];
        
        for (int i = 0; i < arrSize.length; i++) {
            for (int j = 0; j < arrSize.length; j++) {
        if (max < arrSize[i][j]) {
            max = arrSize [i][j];

        if (largeNumTwo < max) {
            arrSize [i][j] = largeNumTwo;
            
        }
        }
        }
        }
        
        System.out.println("Highest Number: " + max);
        System.out.println("Second Highest Number:" + largeNumTwo);
  
 }
}

The output that I get is this:

45 10 44 70 
36 87 35 38 
68 14 30 79 
34 69 50 92 
Highest Number: 92
Second Highest Number:45

The code that I used for the second number is outputting only the first randomly generated number. I am not sure how to fix this.




Aucun commentaire:

Enregistrer un commentaire