我需要从包含1,000个整数的文本文件中获取最小值和最大值。我的程序已设置为计算此文件的中位数和平均值。我想要做的是创建一个变量maxValue
,以便在迭代文本文件时保持最大值。类似于:if maxValue<当前值; currentValue = maxValue。我已经将变量maxValue初始化为0,我现在如何读取第一个值并进行比较?
package week2examples;
import java.util.Arrays;<br>
import stdlib.StdIn;<br>
import stdlib.StdOut;
public class StatisticsArray {
public static double average(int[] numbers) {
int sum = 0;
for (int index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
}
return (double)sum/numbers.length;
}
public static double median(int[] numbers) {
Arrays.sort(numbers);
if (numbers.length % 2 == 0) {
return (numbers[numbers.length/2]+numbers[numbers.length/2-1])/2.0;
}
else {
return numbers[numbers.length/2];
}
}
public static double maximum(int[] numbers) {
int maxValue = 0;
}
public static void main(String[] args) {
StdIn.fromFile ("data/1kints.txt");
int[] numbers = StdIn.readAllInts();
StdOut.println("The average is " + average(numbers));
StdOut.println("The median is " + median(numbers));
}
答案 0 :(得分:0)
public static double maximum(int[] numbers) {
int maxValue = 0;
for (int index = 0; index < numbers.length; index++) {
if (maxValue < numbers[index]){
maxValue = numbers[index];
}
}
return maxValue;
}
这是min的最大值,只需翻转比较符号,我就把它留给你。