previous | start | next

Example 2

Sample Execution:
Input integers will added. Type quit to stop and get the total.

Enter an integer or quit: 1
Enter an integer or quit: two
Invalid input: two
Enter an integer or quit: 2
Enter an integer or quit: quit
Total = 3
   
import java.util.Scanner;
public class ex4
{
  
  public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);
    String input;

    greeting();
    int sum = 0;
    System.out.print("Enter an integer or quit: ");
    input = in.next();
    while(!input.equals("quit")) {
      try {
        int n = Integer.parseInt(input);
        sum += n;
      } catch(NumberFormatException e) {
        System.out.printf("Invalid input: %s\n", input);
      }
      System.out.print("Enter an integer or quit: ");
      input = in.next();
    }
    System.out.printf("Total = %d\n", sum);

  }

  public static void greeting()
  {
      // ... unchanged 
  }
}


previous | start | next