输入并显示后获取最大数量

时间:2019-01-16 10:01:08

标签: java arrays

到目前为止,尚不确定如何获得max方法可以帮助任何人吗? 我需要输入并显示我的输入,然后从输入中获取最大值

import java.util.Scanner;

class Skillsdemo3 {

    static Scanner myinput = new Scanner(System.in);

    public static void main(String[] args) {

        double temperature[] = new double[7];

        enterTemp(temperature);
        displayTemp(temperature);
        maxTemp(temperature); // Method to be implemented
    }

    // Method start
    public static void enterTemp(double temp[]) {
        for (int i = 0; i < temp.length; i++) {
            System.out.println("Max temperature for day" + (i + 1));
            temp[i] = myinput.nextDouble();
        }
    }

    // Method end
    // Method display
    public static void displayTemp(double temp[]) {
        System.out.println(" *** Temperature entered *** ");
        for (int i = 0; i < temp.length; i++) {
            System.out.println(" Day " + (i + 1) + " " + temp[i]);
        } // end method
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用stream轻松实现此目标:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        double temperature[] = new double[] {1D, 20D, 63D, 4D, 8D};
        Arrays.stream(temperature).max().ifPresent(System.out::println); // Finding the maximum and printing
    }
}

答案 1 :(得分:0)

排序数组并获取max元素,请尝试以下代码:

public static double maxTemp(double[] tem) {
    Arrays.sort(tem);
    return tem[tem.length - 1];
}

答案 2 :(得分:0)

您可以使用静态变量在插入或显示的循环中存储最高温度。