简体   繁体   中英

Collecting two integers in a loop to take a weighted average (without an array)

I'm working on an assignment where I need to ask the user for console input for how many items they have, then ask them for two integers (earned and max possible) which I can then calculate the weighted average. It needs to be done with a loop, not an array for this assignment. I have figured out how to gather the number of items and one of the integers, but I don't know how to gather multiple integers within a for loop. Here's the method I have so far:

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

I am able to tally the sum of earned scores with this method, but not the maximum possible scores so that I can take a weighted average.

Thanks!

You need to read the user input (only) integers in a loop and sum each values(weighted and score). You could return one of the sums with something like the following:

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

You will need to read and sum the other number similarly. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM