简体   繁体   中英

While Loop of multiple user-inputted integers

The homework problem is to write a while loop that prompts the user to enter as many integers as they want and to type "q" when done, then print the sum of those integers and the number of entries.

This is what I have so far... It doesn't work if the user inputs more than one integer and I don't know why.

package chapter06lab;

import java.util.Scanner;

public class ProgramF5
{

    public static void main(String[] args)
    {
        Scanner one = new Scanner(System.in);
        System.out.println("Please enter as many valid integers as you wish ('q' to finish): ");
        int a = one.nextInt();
        int count = 0;
        int sum = 0;
        while(one.hasNextInt())
        {
            count++;
            sum =+ a;
        }
        
        System.out.println("The number of entries was: " + count);
        System.out.println("The sum of all numbers entered is: " + sum);
    }

}

Try this:

public static void main(String[] args)
    {
        Scanner one = new Scanner(System.in);
        System.out.println("Please enter as many valid integers as you wish ('q' to finish): ");
        int count = 0;
        int sum = 0;
        while(true)
        {
            String input = one.next();
            if(input.equals("q")){
                break;
            }else{
                try{
                    int x = Integer.parseInt(input);
                    sum+=x;
                    count++;
                }catch (Exception ex){
                    System.out.println("You entered an invalid integer,try again.");
                }
            }
        }

        System.out.println("The number of entries was: " + count);
        System.out.println("The sum of all numbers entered is: " + sum);
    }

To answer your question in the comment:

you are exactly right... after I applied that correction, I met one last problem. The sum that was being printed was only the value of the last inputted integer. So for example, if 35, 45, and 65 were inputted, only 65 was printed as the sum.

You should move your a initialization to inside of while() loop. Why?

Because you need to always get the latest int in the loop, that is why a need to be set inside loop.

Therefor, your while should looks like this:

while(one.hasNextInt())
{
    int a = one.nextInt();
    count++;
    sum =+ a;
}

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