|
IfDemo |
|
1 // Example 2.3 IfDemo.java
2 //
3 //
4 // Copyright 2003 Bill Campbell and Ethan Bolker
5
6
7 // A class illustrating the if-statement. A typical run:
8 //
9 // %> java IfDemo
10 // Enter an integer: 0
11 // If 0 is negative, say hello:
12 // isNegative is false
13 // The integer 0 is zero
14 // Finally: 0 is still nonnegative
15 // because it's zero
16
17 public class IfDemo
18 {
19 public static void main( String[] args )
20 {
21 Terminal terminal = new Terminal(); // for input and output
22
23 // Prompt for and read a single integer.
24 int var = terminal.readInt( "Enter an integer: " );
25
26 // simple if statement
27 terminal.println( "If " + var + " is negative, say hello:" );
28 if (var < 0) {
29 terminal.println( "hello" );
30 }
31
32 // an if-else statement testing a boolean variable
33 boolean isNegative = ( var < 0 );
34 if (isNegative) {
35 terminal.println( "isNegative is true" );
36 }
37 else {
38 terminal.println( "isNegative is false" );
39 }
40
41 // if-else-if statement
42 terminal.print( "The integer " + var + " is ");
43 if (var > 0) {
44 terminal.println("positive");
45 }
46 else if (var < 0) {
47 terminal.println( "negative" );
48 }
49 else { // just one case left!
50 terminal.println( "zero" );
51 }
52
53 // finally, nested if-(if)-else: note the indenting
54 terminal.print( "Finally: " + var + " is still ");
55 if (var >= 0) {
56 terminal.println("nonnegative");
57 if (var == 0 ) {
58 terminal.println("because it's zero ");
59 }
60 }
61 else {
62 terminal.println( "negative" );
63 }
64 }
65 }
66
|
IfDemo |
|