[go: up one dir, main page]

0% found this document useful (0 votes)
37 views2 pages

Calculator

Pyhton code for calculator

Uploaded by

Harjot Singh
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)
37 views2 pages

Calculator

Pyhton code for calculator

Uploaded by

Harjot Singh
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/ 2

import java.util.

Scanner;

public class SimpleCalculator {

// Array to store previous results


private static double[] results = new double[100];
private static int resultCount = 0;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
while (true) {
// Display the menu
System.out.println("Simple Calculator");
System.out.println("1) Add");
System.out.println("2) Subtract");
System.out.println("3) Multiply");
System.out.println("4) Divide");
System.out.println("5) Show Previous Results");
System.out.println("0) Quit");
System.out.print("Choose an option: ");

int choice = scanner.nextInt();


if (choice == 0) {
break;
}

// Get the numbers from the user


System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();

double result = 0;
switch (choice) {
case 1:
result = add(num1, num2);
System.out.println("Result: " + result);
break;
case 2:
result = subtract(num1, num2);
System.out.println("Result: " + result);
break;
case 3:
result = multiply(num1, num2);
System.out.println("Result: " + result);
break;
case 4:
if (num2 != 0) {
result = divide(num1, num2);
System.out.println("Result: " + result);
} else {
System.out.println("Error: Division by zero is not
allowed.");
}
break;
case 5:
showPreviousResults();
continue;
default:
System.out.println("Invalid choice. Please try again.");
continue;
}

// Store the result in the array


if (resultCount < results.length) {
results[resultCount++] = result;
} else {
System.out.println("Result storage is full!");
}
}
scanner.close();
}

// Method for addition


private static double add(double a, double b) {
return a + b;
}

// Method for subtraction


private static double subtract(double a, double b) {
return a - b;
}

// Method for multiplication


private static double multiply(double a, double b) {
return a * b;
}

// Method for division


private static double divide(double a, double b) {
return a / b;
}

// Method to show previous results


private static void showPreviousResults() {
System.out.println("Previous Results:");
for (int i = 0; i < resultCount; i++) {
System.out.println((i + 1) + ": " + results[i]);
}
}
}

You might also like