HarrJ

Day 14 try catch finally

Nov 23rd, 2023
1,469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.87 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Day14A {
  4.     public static void main(String[] args) {
  5.         Scanner sc = new Scanner(System.in);
  6.         double num1, num2;
  7.         String storeValue, opr;
  8.         try {
  9.             System.out.print("Enter 1st value: ");
  10.             storeValue = sc.nextLine();
  11.             num1 = Double.parseDouble(storeValue);
  12.             System.out.print("Enter math operation(+ - * /): ");
  13.             opr = sc.nextLine();
  14.             System.out.print("Enter 2nd value: ");
  15.             storeValue = sc.nextLine();
  16.             num2 = Double.parseDouble(storeValue);
  17.            
  18.             compute(num1, num2, opr);
  19.         } catch (Exception e) {
  20.             System.out.println("Error on the user typed value");
  21.         } finally {
  22.             System.out.println("code complete");
  23.         }
  24.     }
  25.    
  26.     // modified code from Day10A and Day12F file
  27.     static void compute(double n1, double n2, String op){
  28.         boolean computeSuccess = true;
  29.         String printout ="";
  30.         double result = 0;
  31.         switch (op) {
  32.             case "+":
  33.                 result = n1 + n2;
  34.                 break;
  35.             case "-":
  36.                 result = n1 - n2;
  37.                 break;
  38.             case "*":
  39.                 result = n1 * n2;
  40.                 break;
  41.             case "/":
  42.                 try {
  43.                     result = n1 / n2;
  44.                 } catch (Exception e) {
  45.                     printout = "Cannot divide by zero";
  46.                     computeSuccess = false;
  47.                 }
  48.                 break;
  49.             default:
  50.                 printout = "Operator not on list";
  51.                 computeSuccess = false;
  52.         }
  53.         if (computeSuccess) {
  54.             printout = String.format("%.2f %s %.2f = %.4f"
  55.                 , n1, op, n2, result);
  56.         }
  57.         System.out.println(printout);
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment