输入数组java的最小值和最大值?

时间:2017-11-02 04:38:06

标签: java arrays

我有一个功课,但我不太了解Java,我想让这段代码找到最小和最大温度,但我不能使用For和If。有谁能帮我找到这些价值观?

 import java.util.*; // Scanner, Locale
class Temperatur
{
 private static int week;

public static void main (String[] args)
 {
 System.out.println ("TEMPERATUR\n");

 Scanner in = new Scanner (System.in);
 in.useLocale (Locale.US);

 System.out.print ("nr of week: ");
 int nrweek = in.nextInt ();

 System.out.print ("how many week?: ");
 int nrofmeasureperweek = in.nextInt ();

 double[][] t = new double[nrweek + 1][nrofmeasureperweek + 1];

 for (int week = 1; week <= nrweek; week++)
 {
 System.out.println ("temperatur - week " + week + ":");
 for (int measure = 1; measure <= nrofmeasureperweek; measure++)
 t[week][measure] = in.nextDouble ();
 }
 System.out.println ();
 System.out.println ("temperatur:");
 for (int week = 1; week <= nrweek; week++)
 {
 for (int measure = 1; measure <= nrofmeasureperweek; measure++)
 System.out.print (t[week][measure] + " ");
 System.out.println ();
 }
 System.out.println ();

 double[] minT = new double[nrweek + 1];
 double[] maxT = new double[nrweek + 1];

 // Code should be here!






 }
}

在这种情况下,如何编写正确的代码来查找最小和最大温度值!

1 个答案:

答案 0 :(得分:0)

首先,让我们从看到我们拥有的数据开始。我们有温度2d阵列。

double[][] t = new double[nrweek + 1][nrofmeasureperweek + 1];

因此,

  

t [4] [6]是第4周的第6次温度读数。

我们想要填满数组:

double[] minT = new double[nrweek + 1];
double[] maxT = new double[nrweek + 1];

我会做类似的事情:

for(int i=1; i<=nrweek; i++){

    int min = Integer.MAX_VALUE; // initialising
    int max = Integer.MIN_VALUE; // initialising

    for(int j=1; j<=nrofmeasureperweek; j++){
        // min of current number and the min we have seen till now
        min = Math.min(min, t[i][j]); 
        // similar for max
        max = Math.max(max, t[i][j]);
    }

    minT[i] = min;
    maxT[i] = max; // storing back the min and max
}