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

Java Calculator Program

java calculator program

Uploaded by

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

Java Calculator Program

java calculator program

Uploaded by

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

Sure!

Here’s a simple Java program that performs basic arithmetic calculations (addition, subtraction,
multiplication, and division). This example uses the command line for input and output:

```java

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt user for the first number

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

double num1 = scanner.nextDouble();

// Prompt user for the second number

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

double num2 = scanner.nextDouble();

// Prompt user for the operation

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

char operation = scanner.next().charAt(0);

double result;

// Perform the calculation based on the chosen operation

switch (operation) {

case '+':

result = num1 + num2;

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


break;

case '-':

result = num1 - num2;

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

break;

case '*':

result = num1 * num2;

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

break;

case '/':

if (num2 != 0) {

result = num1 / num2;

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

} else {

System.out.println("Error: Division by zero is not allowed.");

break;

default:

System.out.println("Error: Invalid operation.");

break;

scanner.close();

```

### How to Use This Program:

1. **Compile the Program:**


- Save the code in a file named `Calculator.java`.

- Open a terminal or command prompt.

- Navigate to the directory containing `Calculator.java`.

- Compile the program with the command: `javac Calculator.java`.

2. **Run the Program:**

- Execute the compiled program with the command: `java Calculator`.

- Follow the prompts to enter numbers and the desired operation.

This program covers basic arithmetic operations and handles division by zero errors. Feel free to modify
or expand it according to your needs!

You might also like