我的代码有两个问题。 1)当我向我的arraylist添加值时,它没有给我正确的平均值所以我知道我的for循环中的条件是关闭的2)它没有显示我的arrayList中的所有数字。它特别不显示第0个整数。
这是我的代码:
public class CalcAvgDropSmallest {
public static void main(String[] args) {
int lowNum = 0; // # of the lowest numbers to be dropped
double average; // calcuates the mean of the sum and the lowest numbers dropped
ArrayList<Double> inputs= getALInfo();
lowNum = getLowestnum();
average = calculateAvg(inputs, lowNum);
getAvg(inputs, lowNum, average);
}
public static ArrayList<Double> getALInfo() {
ArrayList<Double> inputs = new ArrayList<Double>();
// Read Inputs
Scanner in = new Scanner(System.in);
System.out.println("Please enter 5 - 10 integers, Q to quit: ");
Double vals = in.nextDouble();
while (in.hasNextDouble())
{
inputs.add(in.nextDouble());
}
return inputs;
}
public static int getLowestnum() {
int lowNum = 0;
// Reads Input value for # of lowest values dropped
System.out.println("How many of the lowest values should be dropped?");
Scanner in = new Scanner(System.in);
lowNum = in.nextInt();
return lowNum;
}
public static double calculateAvg(ArrayList<Double> inputs, int lowNum) {
double sum = 0;
double average = 0;
int i = 0;
// Calcuates the average of the array list with the lowest numbers dropped
for (i = 0; i < inputs.size(); i++)
{
if (inputs.get(i) > lowNum) {
sum = sum + inputs.get(i);
}
}
average = (sum / inputs.size());
return average;
}
public static void getAvg(ArrayList<Double> inputs,int n, double average) {
// It's adding all the values and dividing by the size of it, which is a problem
// Also, it's not showing the 0th integer aand just straight to the 1st integer
System.out.println("The average of the numbers " + inputs + " except the lowest " +n+ " is " +average);
}
}
答案 0 :(得分:4)
首先,请编程到function doRequest(url) {
return new Promise(function (resolve, reject) {
request(url, function (error, res, body) {
if (!error && res.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
}
// Usage:
async function main() {
let res = await doRequest(url);
console.log(res);
}
main();
界面(而不是List
具体类型)。其次,您应该确保将读取的每个值添加到ArrayList
。然后,确保你读取终止值(并丢弃它);否则它将在缓冲区中挂起。最后,我将List
传递给方法(而不是在本地重新声明)。像,
Scanner
您可以简化public static List<Double> getALInfo(Scanner in) {
List<Double> inputs = new ArrayList<>();
System.out.println("Please enter 5 - 10 integers, Q to quit: ");
while (in.hasNextDouble()) {
inputs.add(in.nextDouble());
}
in.next();
return inputs;
}
之类的
getLowestnum
然后,您的public static int getLowestnum(Scanner in) {
System.out.println("How many of the lowest values should be dropped?");
return in.nextInt();
}
应对calculateAvg
进行排序并获取List
(丢弃subList
值),最后返回平均值。像,
lowNum
然后public static double calculateAvg(List<Double> inputs, int lowNum) {
Collections.sort(inputs);
return inputs.subList(lowNum, inputs.size()).stream()
.mapToDouble(Double::doubleValue).average().getAsDouble();
}
完成示例
main