Example (a program that determines whether the read integer value is positive, negative, or 0)
filename.rb
import java.util.Scanner;
class Abc
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.print("Integer value");
int n = stdIn.nextInt();
if (n > 0) {
System.out.println("That value is positive");
} else if (n < 0) {
System.out.println("Its value is negative.");
} else {
System.out.println("Its value is 0.");
}
}
}
In this way, describe the control expression next to if and set the condition. If the entered integer value does not meet the "if" condition, the "else if" statement below is displayed, and if none of the conditions are met, the "else" statement is displayed.
Example (a program that determines the number of digits of a read integer value)
filename.java
if (n == 0) {
System.out.println("It is zero.");
}
else if (n >= -9 && n <= 9) {
System.out.println("It is one digit.");
}
else {
System.out.println("2 digits or more.");
}
The "&&" in the control expression of "else if" is the logical product operator. In this case, the control expression of else if becomes "true" when the value of n is -9 or more and 9 or less.
filename.java
if (n <= -10 || n >= 10) {
System.out.println("2 digits or more.");
}
else {
System.out.println("Less than 2 digits.");
}
"If" control expression "||Is the OR operator. In this case, it is "true" when the value of n is -10 or less or 10 or more.
If the evaluation result of the entire expression is clarified only by the evaluation result of the left operand, the evaluation of the right operand is not performed.
filename.java
int min = (a < b) ? a : b;
System.out.println("The smaller value is" + min + "is.");
In this way, "Expression 1"? "Expression 2": "Expression 3" is the conditional operator. If the evaluation of Equation 1 is "true", then Equation 2 is evaluated, and if the evaluation of Equation 1 is "false", Equation 3 is evaluated.
In this case, if a is smaller than b, the value of a is entered in "min", and if a is larger than b, the value of b is entered in "min".
Recommended Posts