0% found this document useful (0 votes)
5 views

Calculator code

This Java program implements a simple calculator that allows users to perform basic arithmetic operations. It prompts the user for two numbers and an operator, handling invalid inputs and division by zero gracefully. The program runs in a loop, continuously accepting input until terminated by the user.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Calculator code

This Java program implements a simple calculator that allows users to perform basic arithmetic operations. It prompts the user for two numbers and an operator, handling invalid inputs and division by zero gracefully. The program runs in a loop, continuously accepting input until terminated by the user.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.util.

Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the calculator!");

while (true) {
double num1 = 0.0, num2 = 0.0;
boolean valid = true;
try {
System.out.print("Enter the first number: ");
num1 = scanner.nextDouble();

System.out.print("Enter the second number: ");


num2 = scanner.nextDouble();
} catch (Exception e) {
valid = false;
System.out.println("Invalid number! Please enter a valid number.");
scanner.next();
}

System.out.print("Enter the operator (+, -, *, /): ");


String operator = scanner.next();

double result;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if(num2 == 0){
System.out.println("Cannot divide by zero!");
valid = false;
}else{
result = num1 / num2;
}
break;
default:
System.out.println("Invalid operator!");
valid = false;
}

if(valid)
System.out.println("Result: " + result);
}
}
}

You might also like