Question

JAVA Ask the user for integers. If the user did not enter an integer, ask again....

JAVA

Ask the user for integers. If the user did not enter an integer, ask again. (Type Safe Input) Keep a running total of the intergers entered (sum). Once the user enters 0, stop looping. Print the sum of all the numbers. Do not use try-catch.

EXAMPLE OUTPUT:

Enter an integer, 0 to stop> [fasdfsa]

Invalid input.

Enter an integer, 0 to stop> [231.342]

Invalid input.

Enter an integer, 0 to stop> [1]

Enter an integer, 0 to stop> [2]

Enter an integer, 0 to stop> [3]

Enter an integer, 0 to stop> [0]

The sum is: 6

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;

public class ValidIntegers {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = 1, sum = 0;
        String s;
        boolean f;

        while (n!=0) {
            System.out.print("Enter an integer, 0 to stop> ");
            s = scan.nextLine();

            f = false;
            for(int i = 0;i<s.length();i++){
                if(!(s.charAt(i)>='0' && s.charAt(i)<='9')){
                    f = true;
                }
            }
            if(f){
                System.out.println("Invalid input.");
            }
            else {
                n = Integer.parseInt(s);
                sum += n;
            }
        }
        System.out.println("The sum is: "+sum);
    }
}

Add a comment
Know the answer?
Add Answer to:
JAVA Ask the user for integers. If the user did not enter an integer, ask again....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT