previous | start | next

Example 1

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
Exception in thread "main" java.lang.NumberFormatException: For input string: "two"
      at java.lang.NumberFormatException.forInputString(Unknown Source)
      at java.lang.Integer.parseInt(Unknown Source)
      at ex3.main(ex3.java:15)
    1   import java.util.Scanner;
    2   public class ex3
    3   {
    4     
    5     public static void main(String[] args)
    6     {
    7       Scanner in = new Scanner(System.in);
    8       String input;
    9   
   10       greeting();
   11       int sum = 0;
   12       System.out.print("Enter an integer or quit: ");
   13       input = in.next();
   14       while(!input.equals("quit")) {
   15        int n = Integer.parseInt(input);
   16         sum += n;
   17         System.out.print("Enter an integer or quit: ");
   18         input = in.next();
   19       }
   20       System.out.printf("Total = %d\n", sum);
   21   
   22     }
   23   
   24     public static void greeting()
   25     {
   26       String msg = 
   27         "Input integers will added. Type quit to stop and get the total.";
   28       System.out.printf("\n%s\n\n", msg);
   29     }
   30   }


previous | start | next