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.
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
import java.util.Scanner; public class SafeTotal { public static void main(String[] args) { Scanner in = new Scanner(System.in); int number, total = 0; while (true) { System.out.print("Enter an integer, 0 to stop> "); try { number = in.nextInt(); total += number; if (number == 0) break; } catch (Exception e) { in.nextLine(); System.out.println("Invalid input."); } } System.out.println("The sum is: " + total); } }
Get Answers For Free
Most questions answered within 1 hours.