Ich muss wissen, wie man eine Gleichung für die Summe ohne Verwendung der ersten beiden Werte meiner ArrayList aus E/A-Datei Ausnahme bilden. Meine Summe sollte nicht die ersten beiden Elemente enthalten, die das Gewicht, 0,5 und die niedrigste Zahl, 3 sind. Alle Werte sind: 0,5, 3, 10, 70, 90, 80, 20. Diese Zahlen stammen aus der Eingabedatei, "Daten.txt". Außerdem muss ich eine "try-with-resources" -Erklärung machen. Ich bin neu dazu und habe gerade gelernt, aber ich wollte wissen, wie ich es auf mein eigenes Programm anwenden kann.E/A-Datei Ausnahme: ArrayList-Werte ohne die ersten beiden Elemente (JAVA)
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();
}
}
Wenn Sie „ersten beiden“ sagen, sind diese Elemente 0 und 1, oder sind sie die beiden kleinsten Elemente? –
@AndyTurner Die ersten beiden Elemente, 0 und 1. –
Sie können einfach an der Position 2 statt 0 beginnen 0 –