[英]Collecting two integers in a loop to take a weighted average (without an array)
我正在做一个作业,我需要询问用户控制台输入中有多少项目,然后询问他们两个整数(赚取的和最大可能的),然后我可以计算出加权平均值。 它需要通过循环而不是此分配的数组来完成。 我已经弄清楚了如何收集项目数和整数之一,但是我不知道如何在for循环中收集多个整数。 这是我到目前为止的方法:
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
我可以使用这种方法计算所得分数的总和,但不能计算最大分数,因此我可以进行加权平均。
谢谢!
您需要循环读取用户输入(仅)整数,并对每个值(加权和得分)求和。 您可以使用以下内容返回总和之一:
public int returnSum() {
Scanner keyboard = new Scanner(System.in);
boolean isValid = false;
int sum1;
while (*NotAtEndOfInput or Some Condition to Signal End of Input*) {
System.out.print("Please enter score: ");
try {
num = keyboard.nextInt();
sum1+=num;
} catch (InputMismatchException ex) {
//In case user enters anything else than integer, catch
//the exception and let the program move ahead to let the user enter again.
System.out.println("Wrong input. Ony integer input will be processed.");
//discards anything which is not int
keyboard.nextLine();
}finally{
//close input stream to avoid memory leak.
keyboard.close();
}
}
return sum1;
}
您将需要类似地阅读和总结其他数字。 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.