【发布时间】:2016-07-29 15:52:33
【问题描述】:
我需要知道如何在不使用来自 I/O 文件异常的 ArrayList 的前两个值的情况下形成总和方程。 我的总和不应该包括前两个元素,即权重 0.5 和最小数字 3。所有值都是:0.5、3、10、70、90、80、20。这些数字来自输入文件,“数据.txt”。另外,我需要做出 try-with-resources 声明。我是新手,刚刚学过,但我想知道如何将它应用到我自己的程序中。
public class CalcWeightedAvgDropLowest {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Double> inputValues = getData();
double weightedAvg = calcWeightedAvg(inputValues);
printResults(inputValues, weightedAvg);
}
public static ArrayList<Double> getData() throws FileNotFoundException {
// Prompts for the input file names
Scanner in = new Scanner(new File("data.txt"));
ArrayList<Double> inputValues = new ArrayList<Double>();
while (in.hasNextDouble())
{
inputValues.add(in.nextDouble());
}
in.close();
return inputValues;
}
public static double calcWeightedAvg(ArrayList<Double> inputValues) throws FileNotFoundException {
// calc weighted av
double sum = 0;
double average = 0;
int i = 0;
double weightavg = 0;
// Calcuates the average of the array list with the lowest numbers dropped
// calculated average is 42.5
for (i = 0; i < inputValues.size(); i++)
{
if (inputValues.get(i) > inputValues.get(1))
{
// **I just need an equation for the sum here w/o the first two values.**
}
}
average = sum /inputValues.size();
weightavg = average * inputValues.get(0);
return weightavg;
}
public static void printResults(ArrayList<Double> inputValues, double weightedAvg) throws FileNotFoundException {
Scanner scnr = new Scanner(System.in);
System.out.print("Output File: ");
String outputFileName = scnr.next();
PrintWriter out = new PrintWriter(outputFileName);
out.print("The weighted average of the numbers is " + weightedAvg + ", when using the data " + inputValues + ", where " +inputValues.get(0)+ " is the weight used, and the average is computed after dropping the lowest " +inputValues.get(1)+ " values.");
out.close();
}
}
【问题讨论】:
-
当你说“前两个”时,这些元素是 0 和 1,还是它们是最小的两个元素?
-
@AndyTurner 前两个元素,0 和 1。
-
你可以从位置 2 而不是 0 开始
-
@LuizAgner 你是不是这个意思
for (i = 2; i < inputValues.size(); i++) -
@OliveBassey 没错。然后它将从
inputValues数组的第三个位置(索引 2)开始,忽略前两个Double数字。
标签: java arraylist average ioexception try-with-resources