Simple Calculator with User Input
Scorri per mostrare il menu
Building a simple calculator is a practical way to reinforce your understanding of user input in Java. By using the Scanner class, you can prompt users for numbers and an operation, then perform calculations based on their input. This approach not only makes your program interactive but also demonstrates how to process different types of data entered by users.
Calculator.java
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849package com.example; import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); double num1 = scanner.nextDouble(); System.out.print("Enter the second number: "); double num2 = scanner.nextDouble(); System.out.print("Enter an operation (+, -, *, /): "); String operation = scanner.next(); double result = 0; boolean validOperation = true; switch (operation) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": if (num2 != 0) { result = num1 / num2; } else { System.out.println("Error: Division by zero."); validOperation = false; } break; default: System.out.println("Error: Unknown operation."); validOperation = false; } if (validOperation) { System.out.println("Result: " + result); } scanner.close(); } }
This calculator program begins by creating a Scanner object to read user input. It prompts the user to enter two numbers, which are read as double values to support both integers and decimals. Next, it asks for an operation symbol (+, -, *, or /). The program uses a switch statement to determine which calculation to perform based on the user's input. If the operation is division, it checks for division by zero to prevent errors. After performing the calculation, the result is printed. If the user enters an invalid operation or attempts to divide by zero, the program displays an appropriate error message. Finally, the Scanner is closed to release system resources.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione