slug
type
status
category
date
summary
tags
password
icon
Let's break down the code step-by-step:
- This line imports the
Scannerclass from thejava.utilpackage, which allows us to read user input.
- This line defines a public class named
SimpleCalculator. In Java, all executable code must be within a class.
- This is the main method, the entry point of any Java application. The
mainmethod is where the program begins execution.
publicmeans the method is accessible from outside the class.
staticmeans the method belongs to the class, not instances of it.
voidmeans the method does not return a value.
String[] argsis an array ofStringarguments passed to the program (not used in this code).
- This line creates a
Scannerobject namedscanner, which reads input from the standard input stream (System.in).
- This line starts an infinite loop. The loop will continue to execute indefinitely unless explicitly broken.
System.out.printlnprints the prompt "Enter first number:" to the console.
scanner.nextDouble()reads the next double value entered by the user and assigns it tonum1.
- Similar to the previous prompt, this line asks the user for a second number and assigns the entered value to
num2.
- This line prompts the user to enter an operator (
+,,, or/).
scanner.next()reads the next input as aString.
charAt(0)extracts the first character of thatStringand assigns it tooperator.
- These lines initialize two variables:
result(to store the calculation result) andvalidOperation(a flag to indicate if the operation is valid).
- This
switchstatement performs different calculations based on the value ofoperator. - If
operatoris'+', it addsnum1andnum2and assigns the result toresult. - If
operatoris'-', it subtractsnum2fromnum1. - If
operatoris'*', it multipliesnum1andnum2. - If
operatoris'/', it checks ifnum2is not zero (to avoid division by zero). If it's not zero, it dividesnum1bynum2; otherwise, it prints an error message and setsvalidOperationtofalse. - If the operator is none of the above, it prints "Invalid operator!" and sets
validOperationtofalse.
- This
ifstatement checks if the operation was valid (i.e., no errors occurred). If it was valid, it prints the result.
- The closing braces
}mark the end of thewhileloop, themainmethod, and theSimpleCalculatorclass.
In summary, this code implements a simple calculator that:
- Continuously prompts the user for two numbers and an operator.
- Performs the requested operation.
- Displays the result or an error message if the operation is invalid (e.g., division by zero or an unrecognized operator).
- 作者:现代数学启蒙
- 链接:https://www.math1234567.com/article/simplecalculator
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章











