-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLecture21TernaryOp.java
More file actions
67 lines (61 loc) · 1.29 KB
/
Lecture21TernaryOp.java
File metadata and controls
67 lines (61 loc) · 1.29 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Scanner;
/**
* Lecture 21
* using the ternary operator
*
* @author PMCampbell
* @version 2020-12-01
*/
public class Lecture21TernaryOp {
public static void main(String[] args) {
scopeProblem();
solutionOne();
ternarySolution();
System.out.println(ternaryPlural(1));
System.out.println(ternaryPlural(35));
}
/**
* this method won't compile,
* max is out of scope for the print
* comment it out to compile
*/
public static void scopeProblem() {
int x = 5, y=15;
if (x > y) {
int max = x;
}
else {
int max = y;
}
System.out.println("The max is " + max);
}
/**
* solution 1 for scopeProbem()
*/
public static void solutionOne() {
int x = 5, y=15, max;
if (x > y) {
max = x;
}
else {
max = y;
}
System.out.println("The max is " + max);
}
/**
* solution 2 for scopeProbem()
* use the ternary operator
*
*/
public static void ternarySolution() {
int x = 55, y=15;
System.out.println("The max is " + ( x > y ? x : y));
}
/**
* example using the ternary operator
*
*/
public static String ternaryPlural(int cookies) {
return "There " + (cookies > 1 ? "are " + cookies + " cookies" : "is one cookie");
}
}