-1

I am trying to get a max and min value out of a random number array while the user inputs Y to continue the program. Would I want to test for min and max in my random number method or make min and max its own method?

I've tried research and I have been working on this for hours.

package lab10p1;
import java.util.*;
import java.util.Random;


public class Lab10p1 {
public static final int ROW = 5;
public static final int COL = 6;
public static final int MIN = 0;
public static final int MAX = 100;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 

{

    Scanner scan=new Scanner(System.in);
System.out.println("Do you want to start Y/N?");
char c =scan.next().charAt(0);

while(c=='y'||c=='Y')
{

 int[][] a = new int[ROW][COL]; 
 randArray(a, ROW, COL, MIN, MAX);
 int smallest;


System.out.println(min);
c=scan.next().charAt(0);

}


}
  public static int randArray(int[][] matrix, int row, int col, int low, int up)
  {     
      Random rand = new Random(); 
       int min = matrix[0][0]; 
  for (int r = 0; r < row; r++)
  {          
   for (int c = 0; c < col; c++)   
   {       
     if(matrix[r][c] < min) {               
              min = matrix[r][c];}
      int random=matrix[r][c] = rand.nextInt(up - low + 1) + low; 
  System.out.print(" "+random); 
   }       
   System.out.println();
  }
  return min;
  }
 }    

The expected output is

12 13 53 23 53 42
34 56 65 34 23 45 
2  64 23 42 11 13
87 56 75 34 56 92
23 45 23 42 32 12
The difference between the max value 94 and the min value 2 = 92 
Do you want to continue(Y/N): y
azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • I think what you are most likely to get with this question, is people's opinions. Does it work they way you currently have it programmed? You could make your own min/max functions. It might be easier to read doing it that way. Also, take a look at Math.min() and Math.max(). – Chris K May 01 '19 at 18:36
  • It does not return anything right now. Ill research those – mikegreene123 May 01 '19 at 18:38
  • Possible duplicate of [Finding the max/min value in an array of primitives using Java](https://stackoverflow.com/questions/1484347/finding-the-max-min-value-in-an-array-of-primitives-using-java) – Benjamin Urquhart May 01 '19 at 18:38

1 Answers1

0

You can use Arrays.stream(), IntStream.min() and IntStream.max() for this:

min:

private static int arrayMin(int[][] a) {
    return Arrays.stream(a)
            .mapToInt(r -> IntStream.of(r).min().getAsInt())
            .min().getAsInt();
}

max:

private static int arrayMax(int[][] a) {
    return Arrays.stream(a)
            .mapToInt(r -> IntStream.of(r).max().getAsInt())
            .max().getAsInt();
}

Both methods looking for the min/max of each row and mapping this result to another array and getting the min/max of this.

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56