我需要知道如何在不使用I / O文件异常的ArrayList的前两个值的情况下形成总和的等式。 我的总和不应该包括前两个元素,即权重,0.5和最小数字,3。所有值都是:0.5,3,10,70,90,80,20。这些数字来自输入文件,“ data.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 :(得分:0)
您可以使用以下方式查看从2到最后的列表元素:
List<Double> view = inputValues.subList(2, inputValues.size());
(假设您在列表中至少有2个元素)。
然后将calcWeightedAverage
的参数更改为List<Double>
,然后传递view
:
calcWeightedAvg(view);