slug
type
status
category
summary
date
tags
password
icon
Let's break down the code step-by-step:
- This line imports the
Scanner
class from thejava.util
package, 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
main
method is where the program begins execution.
public
means the method is accessible from outside the class.
static
means the method belongs to the class, not instances of it.
void
means the method does not return a value.
String[] args
is an array ofString
arguments passed to the program (not used in this code).
- This line creates a
Scanner
object 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.println
prints 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 thatString
and 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
switch
statement performs different calculations based on the value ofoperator
. - If
operator
is'+'
, it addsnum1
andnum2
and assigns the result toresult
. - If
operator
is'-'
, it subtractsnum2
fromnum1
. - If
operator
is'*'
, it multipliesnum1
andnum2
. - If
operator
is'/'
, it checks ifnum2
is not zero (to avoid division by zero). If it's not zero, it dividesnum1
bynum2
; otherwise, it prints an error message and setsvalidOperation
tofalse
. - If the operator is none of the above, it prints "Invalid operator!" and sets
validOperation
tofalse
.
- This
if
statement 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 thewhile
loop, themain
method, and theSimpleCalculator
class.
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/simplecalculator
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。
相关文章