- import java.util.Scanner;
- import java.io.*;
- public class TechFact555Calculator {
- public static void main(String[] args) {
- Scanner reader = new Scanner(System.in);
- System.out.print("Enter two numbers: ");
- // nextDouble() reads the next double from the keyboard
- double first = reader.nextDouble();
- double second = reader.nextDouble();
- System.out.print("Enter an operator (+, -, *, /): ");
- char operator = reader.next().charAt(0);
- double result;
- try {
- switch(operator){
- case '+':
- result = first + second;
- break;
- case '-':
- result = first - second;
- break;
- case '*':
- result = first * second;
- break;
- case '/':
- result = first / second;
- break;
// operator doesn't match any case constant (+, -, *, /)- default:
- System.out.printf("Error! operator is not correct");
- return;
- }
- System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
- } catch(Exception e) {
- System.out.print("Exception occurred " + e);
- }
- }
- }
Thursday, April 23, 2020
Java program to handle arithmetic [Calculator] with Exception using Scanner
Labels:
Arithmetic Opertations,
Calculator,
Exception,
Java,
Scanner,
User Input
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment