-
Notifications
You must be signed in to change notification settings - Fork 6
/
Conditionals.java
executable file
·48 lines (40 loc) · 1.55 KB
/
Conditionals.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.Scanner;
public class Conditionals {
public static void main(String[] args) {
System.out.print("Enter an integer: ");
Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();
if ((num % 2) == 0) {
System.out.printf("%d is even.%n", num);
} else {
System.out.printf("%d is odd.%n", num);
}
// Boolean expressions
boolean numIsEven = (num % 2) == 0;
// Notice the use of {} even for single statements -
// - good idea always to use {}
if (numIsEven) {
System.out.println("I like even numbers.");
} else {
System.out.println("I'm ambivalent about odd numbers.");
}
// The if-else statements above can be combined using blocks
if (numIsEven) {
System.out.printf("%d is even.%n", num);
System.out.println("I like even numbers.");
} else {
System.out.printf("%d is odd.%n", num);
System.out.println("I'm ambivalent about odd numbers.");
}
// Beware that assignment is actually an expression.
// An assignment has the value of the assignment.
// This is why chained assignments work.
System.out.println("\n************* CAUTION! *************");
if (numIsEven = true) {
System.out.println("This statement will always execute.");
} else {
System.out.println("This statement will never execute.");
}
System.out.println();
}
}