我四处寻找答案,但没有太多运气试图让以下工作。
我目前正在上一门介绍性编程课程,并且遇到了一个练习,我需要编写两个函数(即一个返回值的方法)
a) 返回最大值和
b) 中值,来自双精度值数组。
下面是我在哪里的代码。我已经成功创建了一个方法,该方法允许用户输入数组元素的数量并用一个值初始化它们。但是,我很难让计算最大值的方法起作用。我被明确告知要使用 Math.max 方法。但是,每当我尝试运行代码时,在用户初始化数组后都会收到以下错误消息:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method max(double, double) in the type Math is not applicable for the arguments (double, double[])"
根据我在 API 中阅读的内容,Math.max
可以处理双重类型。我对如何解决这个问题有点不知所措。我觉得我需要创建一个循环,但我的印象是foreach
循环是等价的。
所有回复将不胜感激。
package com.gc01.lab2;
import java.util.Scanner;
public class exercise22 {
private static double [] numberInput(){
Scanner input = new Scanner (System.in);
System.out.println("How many numbers are in the array?");
int count = input.nextInt();
double [] array = new double [count];
for (int i = 0; i < count; ++i){
System.out.println("Enter number " + i + ": ");
array [i] = input.nextDouble();
}
return array;
}
private double maximum (double [] array){
double max = 0.0;
for (double value : array){
max = Math.max(0.0, array);
}
return max;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
final exercise22 object = new exercise22 ();
System.out.println("The maximum number inputted is " +
object.maximum(object.numberInput()));
}
}