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

Practical3 Prakash

The document describes a Java program that takes an arithmetic operator and two numbers from the user and performs the operation, displaying the result. It accepts the operator as a string and the numbers, uses a switch statement to perform the correct operation, and handles errors such as division by zero.

Uploaded by

prakashnotfound
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Practical3 Prakash

The document describes a Java program that takes an arithmetic operator and two numbers from the user and performs the operation, displaying the result. It accepts the operator as a string and the numbers, uses a switch statement to perform the correct operation, and handles errors such as division by zero.

Uploaded by

prakashnotfound
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Practical 3 :

Our goal is to develop a Java program that takes an arithmetic operator as a string and performs the corresponding
operation on two numbers provided by the user. The program will be user-friendly, allowing them to input the operator and
numbers and display the result of the operation.

The task is to create a console-based Java program that:


Accepts an arithmetic operator as a string input (e.g., "+", "-", "*", "/").
Accepts two numeric values as inputs.
Performs the specified arithmetic operation on the given numbers.
Displays the result of the operation to the user.

Program :

import java.util.Scanner;

public class practical3 {


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

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


System.out.println("Available operators: + (addition), -
(subtraction), * (multiplication), / (division)");
System.out.println("Please enter the operator followed by two
numbers.");

System.out.print("Operator (+, -, *, /): ");


String operator = scanner.nextLine();

System.out.print("First number: ");


double num1 = scanner.nextDouble();

System.out.print("Second number: ");


double num2 = scanner.nextDouble();

double result = 0;
boolean isValidOperator = true;

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
} else {
isValidOperator = false;
System.out.println("Error: Cannot divide by zero.");
}
break;
default:
isValidOperator = false;
System.out.println("Error: Invalid operator. Please use
one of the following: +, -, *, /");
}

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

scanner.close();
}
}

Output :

You might also like