Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Simple Calculator with User Input | Building Interactive Programs
Java User Input Essentials

bookSimple Calculator with User Input

Svep för att visa menyn

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

Calculator.java

copy
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
package 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.

question mark

What is the main benefit of using Scanner in a calculator program?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 3. Kapitel 1
some-alt