课程: Learning Java 17

Operators in Java - Java教程

课程: Learning Java 17

Operators in Java

- Thinking back to the decision block in our control flow, we have three main components. We have a condition, the code that gets run if the condition is true, and the code that gets run if the condition is false. To simplify our condition, we can write it out with the less than sign instead of plain English. This is closer to what it will look like in our code. Ultimately, the value of inputted num or the number that the user inputs will determine which code statement is run, which is exactly what we want. We call the less than sign a relational operator. Its inputs are inputted num and five. The relational operator states a comparison between these two inputs and the result of this comparison will be true or false. Since the inputted num less than five comparison evaluates to a Boolean, we call it a Boolean expression. A Boolean expression can be used as a condition for decision blocks. Less than is just one relational operator. There are many others we could use instead. This is a list of the other relational operators. If we wanted to make our relational operator be less than or equal to, instead of just less than, we can add an equal sign. This would test if inputted num is less than or equal to five. Similarly, for the greater than sign, we would just add an equal sign to test if the inputted num is greater than or equal to eight. To check for equality, we can use the double equal signs. This would check if inputted num is equal to eight. If it is, the statement would be true, otherwise it would be false. To check for inequality, we use an exclamation point and an equal sign. In this case, the statement would be true as long as inputted num does not equal three. It would be false in the case that inputted num equals three. Ultimately, a condition in a decision block evaluates to true or false depending on some variable. That's what makes it a condition that can be evaluated during the program's execution, and manipulate a program's control flow.

内容