Java 在循环中收集两个整数以获得加权平均值(无数组)

Java 在循环中收集两个整数以获得加权平均值(无数组),java,loops,console,Java,Loops,Console,我正在做一个作业,我需要向用户询问控制台输入他们有多少项,然后向他们询问两个整数(挣值和最大可能值),然后我可以计算加权平均值。对于此分配,需要使用循环而不是数组来完成。我已经知道了如何收集项数和一个整数,但我不知道如何在for循环中收集多个整数。以下是我到目前为止的方法: public static void homework() { Scanner console = new Scanner(System.in); System.out.print(

我正在做一个作业,我需要向用户询问控制台输入他们有多少项,然后向他们询问两个整数(挣值和最大可能值),然后我可以计算加权平均值。对于此分配,需要使用循环而不是数组来完成。我已经知道了如何收集项数和一个整数,但我不知道如何在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);
    }
publicstaticvoid作业(){
扫描仪控制台=新扫描仪(System.in);
系统输出打印(“作业数量?”);
int totalAssignments=console.nextInt();
整数和=0;

对于(int i=1;i,您需要读取循环中的用户输入(仅)整数,并对每个值求和(加权和分数)。您可以使用以下内容返回其中一个和:

        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;
        }

您需要以同样的方式读取和求和其他数字。希望这能有所帮助。

为什么不只取数字而不是算术?作业要求我们使用循环进行累积求和。