返回最小值和最大值

时间:2019-05-01 18:20:33

标签: java arrays methods

当用户输入Y继续执行程序时,我试图从随机数数组中获取最大值和最小值。我要用随机数方法测试min和max还是将max和max设置为自己的方法?

我已经尝试研究,并且已经为此工作了几个小时。

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;
  }
 }    

预期输出为

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

1 个答案:

答案 0 :(得分:0)

您可以为此使用Arrays.stream()IntStream.min()IntStream.max()

分钟

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

最大

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

这两种方法都查找每行的最小值/最大值,然后将结果映射到另一个数组,并获取其最小值/最大值。

相关问题