Simple Calculator Java, C++, Python
👤 Sharing: AI
Okay, here are simple calculator programs written in Java, C++, and Python, along with explanations.
**1. Java**
```java
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create a Scanner object to read input from the console
System.out.println("Simple Calculator");
System.out.println("Enter first number:");
double num1 = scanner.nextDouble(); // Read the first number as a double
System.out.println("Enter an operator (+, -, *, /):");
char operator = scanner.next().charAt(0); // Read the operator as a character
System.out.println("Enter second number:");
double num2 = scanner.nextDouble(); // Read the second number as a double
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("Error: Division by zero is not allowed.");
return; // Exit the program if division by zero is attempted
}
result = num1 / num2;
break;
default:
System.out.println("Error: Invalid operator.");
return; // Exit the program if an invalid operator is entered
}
System.out.println("Result: " + result);
scanner.close(); // Close the Scanner to prevent resource leaks
}
}
```
**Explanation:**
1. **Import Scanner:** `import java.util.Scanner;` imports the `Scanner` class, which is used to get input from the user.
2. **Create Scanner Object:** `Scanner scanner = new Scanner(System.in);` creates a `Scanner` object that reads input from the standard input stream (the console).
3. **Get Input:** The program prompts the user to enter the first number, the operator, and the second number. `scanner.nextDouble()` reads the numbers as `double` values, allowing for decimal inputs. `scanner.next().charAt(0)` reads the operator as a character.
4. **Switch Statement:** A `switch` statement is used to perform the calculation based on the operator. Each `case` corresponds to a different operator.
5. **Division by Zero Check:** Before dividing, the code checks if the second number (`num2`) is zero. If it is, an error message is printed, and the program exits using `return`. This prevents a runtime error.
6. **Invalid Operator Check:** The `default` case in the `switch` statement handles cases where the user enters an invalid operator. An error message is printed, and the program exits.
7. **Print Result:** The calculated result is printed to the console.
8. **Close Scanner:** `scanner.close();` closes the `Scanner` object to release resources. This is good practice.
**2. C++**
```c++
#include <iostream>
using namespace std;
int main() {
double num1, num2, result;
char op;
cout << "Simple Calculator" << endl;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter an operator (+, -, *, /): ";
cin >> op;
cout << "Enter second number: ";
cin >> num2;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
cout << "Error: Division by zero is not allowed." << endl;
return 1; // Exit the program with an error code
}
result = num1 / num2;
break;
default:
cout << "Error: Invalid operator." << endl;
return 1; // Exit the program with an error code
}
cout << "Result: " << result << endl;
return 0; // Exit the program successfully
}
```
**Explanation:**
1. **Include iostream:** `#include <iostream>` includes the iostream library, which is needed for input and output operations (like `cout` and `cin`).
2. **Using namespace std:** `using namespace std;` avoids the need to prefix standard library elements (like `cout` and `cin`) with `std::`.
3. **Declare Variables:** The code declares variables to store the two numbers (`num1`, `num2`), the operator (`op`), and the result (`result`). All numbers are declared as `double` to handle decimal values.
4. **Get Input:** The program prompts the user to enter the first number, the operator, and the second number using `cout` and reads the input using `cin`.
5. **Switch Statement:** A `switch` statement is used to perform the calculation based on the operator.
6. **Division by Zero Check:** Similar to the Java version, there's a check to prevent division by zero. If `num2` is 0, an error message is printed, and the program exits with a non-zero return code (`return 1;`). This indicates an error.
7. **Invalid Operator Check:** The `default` case handles invalid operators, printing an error message and exiting with an error code.
8. **Print Result:** The calculated result is printed to the console.
9. **Return 0:** `return 0;` indicates that the program executed successfully.
**3. Python**
```python
def simple_calculator():
"""A simple calculator program."""
try:
num1 = float(input("Enter first number: "))
operator = input("Enter an operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("Error: Division by zero is not allowed.")
return # Exit the function
result = num1 / num2
else:
print("Error: Invalid operator.")
return # Exit the function
print("Result:", result)
except ValueError:
print("Error: Invalid input. Please enter numbers only.")
except Exception as e: # Catch any other potential errors
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
print("Simple Calculator")
simple_calculator()
```
**Explanation:**
1. **`def simple_calculator():`**: Defines a function called `simple_calculator` to encapsulate the calculator's logic. Using a function makes the code more organized and reusable.
2. **`"""A simple calculator program."""`**: This is a docstring, a multiline string used for documenting the function.
3. **`try...except` Block:** The code is wrapped in a `try...except` block to handle potential errors. This makes the program more robust.
* **`ValueError`:** Catches errors that occur when the user enters non-numeric input (e.g., letters instead of numbers). `float(input(...))` will raise a `ValueError` if the input cannot be converted to a float.
* **`Exception as e`:** Catches any other type of exception that might occur. This provides a generic error handling mechanism. `e` is the exception object itself, and we print it to get more details about the error.
4. **`input()` Function:** The `input()` function is used to get input from the user. The `float()` function converts the input to a floating-point number (allowing for decimal values).
5. **`if...elif...else` Structure:** An `if...elif...else` structure is used to determine which operation to perform based on the operator entered by the user.
6. **Division by Zero Check:** Before dividing, the code checks if `num2` is equal to 0. If it is, an error message is printed, and the function returns (exiting the calculator logic).
7. **Invalid Operator Check:** The `else` block handles the case where the user enters an invalid operator.
8. **`print("Result:", result)`:** Prints the calculated result to the console.
9. **`if __name__ == "__main__":`**: This is a standard Python construct. It ensures that the `simple_calculator()` function is called only when the script is run directly (not when it's imported as a module into another script).
10. **`print("Simple Calculator")`**: Prints the title of the program.
11. **`simple_calculator()`**: Calls the `simple_calculator()` function to start the calculator.
Key improvements in the Python example:
* **Error Handling:** The `try...except` block makes the code more robust by handling potential errors like invalid input.
* **Function:** Encapsulating the calculator logic in a function makes the code more organized and reusable.
* **Docstring:** The docstring provides documentation for the function.
* **`if __name__ == "__main__":`**: Ensures that the calculator logic is executed only when the script is run directly.
These examples cover the basics of creating a simple calculator in Java, C++, and Python. They demonstrate how to get input from the user, perform basic arithmetic operations, and handle potential errors. Remember to compile and run the Java and C++ code before executing them. The Python code can be run directly.
👁️ Viewed: 7
Comments