Thursday, April 23, 2020

Java program to handle arithmetic [Calculator] with Exception using Scanner


  1. import java.util.Scanner;
  2. import java.io.*;

  3. public class TechFact555Calculator {
  4.     public static void main(String[] args) {
  5.         Scanner reader = new Scanner(System.in);
  6.         System.out.print("Enter two numbers: ");
  7.         
  8.         // nextDouble() reads the next double from the keyboard
  9.         double first = reader.nextDouble();
  10.         double second = reader.nextDouble();
  11.         System.out.print("Enter an operator (+, -, *, /): ");

  12.         char operator = reader.next().charAt(0);
  13.         double result;
  14.         try {
  15.             switch(operator){

  16.             case '+':
  17.                 result = first + second;
  18.                 break;

  19.             case '-':
  20.                 result = first - second;
  21.                 break;

  22.             case '*':
  23.                 result = first * second;
  24.                 break;

  25.             case '/':
  26.                 result = first / second;
  27.                 break;

  28.             // operator doesn't match any case constant (+, -, *, /)
  29.             default:
  30.                 System.out.printf("Error! operator is not correct");
  31.                 return;
  32.             }
  33.             System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
  34.         } catch(Exception e) {
  35.             System.out.print("Exception occurred " + e);
  36.         }
  37.     }
  38. }

No comments:

Post a Comment