Selection Statements

Introduction to Computers and
Programming in JAVA: V22.0002
Control structures:
if-else statements and
switch statements
 2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
2
Relational Operators (revisited)
Operator
Meaning
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
==
Equal to
!=
Not Equal to
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
3
Strings: example 1
public class string_example
//String concatenation
{
public static void main(String[] args)
{
//String is a class
String s1 = " The Cat ";
String s2 = " in the Hat";
String s3 = s1 + s2;//concatenation example
System.out.println(s3);
}
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
4
Strings -- example 2
import javax.swing.JOptionPane; //not in java.lang
public class string_example2
//concatenate two strings read from input
{
public static void main(String[] args)
{
String s1 = JOptionPane.showInputDialog("type 1st input");
String s2 = JOptionPane.showInputDialog("type 2nd input");
String s3 = s2 + s1;
System.out.println(s3);
System.exit(0); //required for JOptionPane
}
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
// less than five!!
import javax.swing.JOptionPane;
public class less_than_5{
public static void main(String args[]) {
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Enter a number from 1 to 10:", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
// Convert the string into an int value
int num = Integer.parseInt(numString);
// Display the result in a message dialog box
if ( num < 5 )
System.out.println(" The number " + num + " is less than five.");
else
if (num == 5)
System.out.println(" The number " + num + " is equal to five.");
else
System.out.println(" The number " + num + " is greater than five.");
System.exit(0);
}
 2000 Prentice Hall, Inc. All rights reserved. (modified)
5
6
Another example: writing a program in class
about people’s ages:
• Program should ask user to input his or her
age
• Program should determine and print the
following based on the age:
– A person is a teenager if their age is 13 through
19
– You are too old to be a teenager
– You are too young to be a teenager
 2000 Prentice Hall, Inc. All rights reserved. (modified)
// ages
import javax.swing.JOptionPane;
Nested if-else
public class age {
public static void main(String args[]) {
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Enter your age:", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
int age = Integer.parseInt(numString);
System.out.println(" Your age is " + age + ".");
// Convert the string into an int value
/* A person is a teenager if their age is 13 thu 19 */
if (age > 12)
if (age <20)
System.out.println("You are a teenager!\n");
else
System.out.println("You are too old to be a teenager!\n");
else
System.out.println("You are too young to be a teenager!\n");
System.exit(0);
}
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
7
// grades: example #2
import javax.swing.JOptionPane;
Nested if-else
public class grades_example2 {
public static void main(String args[]) {
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Enter your grade (0-100):", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
// Convert the string into an int value
int grade = Integer.parseInt(numString);
System.out.println("Your grade is " + grade + ".");
if (grade >= 90)
System.out.println("You got an \"A\".\n");
else if (grade >= 80)
System.out.println("You got a \"B\".\n");
else if (grade >= 70)
System.out.println("You got a \"C\".\n");
else if (grade >= 60)
System.out.println("You passed but you need a tutor.\n");
else
System.out.println("You failed.\n");
System.exit(0);
}
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
8
9
switch Multiple-Selection Structure
• Used when testing a variable or expression for
EQUALITY:
•
( >, <, >=, <=)
– tests separately for each of the constant integral values it
may assume.
• Preferred over if else in situations:
– where you are testing the same expressions for equality with
many different values.
• Allows you to perform different actions for each
test.
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
10
switch Multiple-Selection Structure
switch (expression) {
case value1:
action(s);
break;
keyword switch
expression can be a variable or
a more complicated expression
case value2:
action(s);
break;
…
default:
actions(s);
break;
could use more than one case;
if the same actions are required
actions within a single case do
not need brackets
the default case will be executed
in the event that no other case is
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
switch Multiple-Selection
FlowChart
True
Case a
action(s)
break
Case b
Case b
action(s)
break
Default
Default
action(s)
Case a
false
True
false
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
11
12
beware of “fall through”
• If you forget to use the break keyword
between cases, unexpected things may
happen.
• Once a case tests true, all the statements
following that case, will be executed until
the next break.
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
Nested if-else
//dice_using_if
import javax.swing.*;
public class dice_using_if {
public static void main( String args[] )
{
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Roll the die!! (1-6):", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
// Convert the string into an int value
int roll = Integer.parseInt(numString);
System.out.println(" You rolled a " + roll + ".");
if (roll == 1 )
System.out.println("You rolled a one! Try again! \n");
else if (roll == 2 )
System.out.println("You rolled a two! Too bad! \n");
else if (roll == 3 )
System.out.println("You rolled a three! Better luck next time! \n");
else if (roll == 4 )
System.out.println("You rolled a four! Sorry! \n");
else if (roll == 5 )
System.out.println("You rolled a five! Way to go!!\n");
else if (roll == 6 )
System.out.println("You rolled a six! I guess you win ...\n");
else
System.out.println("This is some wierd die! \n");
System.exit( 0 );
// terminate application
}}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
13
Switch statements
// dice_using_switch
import javax.swing.*;
public class dice_using_switch {
public static void main( String args[] )
{
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Roll the die!! (1-6):", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
// Convert the string into an int value
int roll = Integer.parseInt(numString);
System.out.println(" You rolled a " + roll + ".");
switch ( roll ) {
case 1:
System.out.println("You rolled a one! Try again! \n");
break;
case 2:
System.out.println("You rolled a two! Too bad! \n");
break;
case 3:
System.out.println("You rolled a three! Better luck next time! \n");
break;
case 4:
System.out.println("You rolled a four! Sorry! \n");
break;
case 5:
System.out.println("You rolled a five! Way to go!!\n");
break;
case 6:
System.out.println("You rolled a six! I guess you win ...\n");
break;
default:
System.out.println("This is some wierd die! \n");
} // end switch
System.exit( 0 );
// terminate application
} // end main
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
14
Switch statements
// switch example #2
import javax.swing.*;
public class switch_example2 {
public static void main( String args[] )
{
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Pick a number from 1-6:", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
int pick = Integer.parseInt(numString); // Convert the string into an int value
System.out.println(" You picked a " + pick + ".");
switch (pick)
{
case
1:
System.out.println("You entered 1!\n");
break;
case
2:
case
3:
System.out.println("You entered a 2 or a 3!\n");
break;
case
4:
case
5:
case
6:
System.out.println("You entered a 4, 5, or a 6!\n");
break;
default:
System.out.println("You did not enter an 1,2, 3, 4, 5 or 6!\n");
break;
} /* end switch */
System.exit( 0 );
} }
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
15
Nested if-else
// grades: example #1
import javax.swing.JOptionPane;
public class grades_example1 {
public static void main(String args[]) {
// Prompt the user to enter a number:
String numString = JOptionPane.showInputDialog(null,
"Enter your grade (0-100):", "Input Window Demo",
JOptionPane.QUESTION_MESSAGE);
// Convert the string into an int value
int grade = Integer.parseInt(numString);
System.out.println(" Your grade is " + grade + ".");
if (grade > 60)
if (grade > 70)
System.out.println("You passed.\n");
else
System.out.println("You passed but you need a tutor.\n");
else
System.out.println("You failed.\n");
System.exit(0);
} }
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
16
17
The boolean Type and Operators
boolean lightsOn = true;
boolean lightsOn = false;
boolean b = (1 > 2);
• && (and)
• || (or)
•!
(not)
(1 < x) && (x < 100)
(1 < x) ||(x < 100)
!(1<x)
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
18
Comparison Operators
Operator Name
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
==
equal to
!=
not equal to
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
19
Boolean Operators
Operator Name
!
not
&&
and
||
or
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
20
Truth Table for Operator !
Truth Table for Operator !
Operand !Operand
true
false
false
true
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
21
Truth Table for Operator &&
Operand1
Operand2
Operand1 && Operand2
false
false
false
false
true
false
true
false
false
true
true
true
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
22
Truth Table for Operator ||
Operand1 Operand2 Operand1 || Operand2
false
false
false
false
true
true
true
false
true
true
true
true
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
23
Increment and
Decrement Operators
suffix
x++; // Same as x = x + 1;
prefix
++x; // Same as x = x + 1;
suffix
x––; // Same as x = x - 1;
prefix
––x; // Same as x = x - 1;
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
24
Increment and
Decrement Operators
• PostDecrement Operator (x--):
– use the current value of x in the expression.
Then, decrease by 1.
• PreDecrement Operator (--x):
– Decrease x by 1. Then, use the new value of x
in the expression.
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
25
Increment and
Decrement Operators, cont.
int i=10;
int newNum = 10*i++;
int i=10;
int newNum = 10*(++i);
Equivalent to
Equivalent to
int newNum = 10*i;
i = i + 1;
i = i + 1;
int newNum = 10*i;
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
26
Increment and
Decrement Operators, cont.
Using
increment and decrement operators
makes expressions short
but it also makes them complex and
difficult to read.
Avoid
using these operators in
expressions that
modify multiple variables, or the same
variable for multiple times such as
this:
int k = ++i + I;
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
27
What's the output of this program?
public class shortcut_operators {
public static void main(String[] args) {
// declare variables
int x = 10;
int y = 5;
int z = 3;
System.out.println("x = "+x+", y = "+y+", z = "+z+ "\n");
x++;;
y += x;
z *= x;
System.out.println("Now x = "+x+", y = "+y+", z = "+z+ "\n");
x--;
y *= x;
z %= x;
System.out.println("And now x = "+x+", y = "+y+", z = "+z+ "\n");
System.exit(0);
}
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .
28
What's the output of this program?
public class shortcut_operators {
public static void main(String[] args) {
// declare variables
int x = 10;
int y = 5;
int z = 3;
x = 10, y = 5, z = 3
Now x = 11, y = 16, z = 33
System.out.println("x = "+x+", y = "+y+", z = "+z+ "\n");
And now x = 10, y = 160, z = 3
x++;;
y += x;
z *= x;
Press any key to continue...
System.out.println("Now x = "+x+", y = "+y+", z = "+z+ "\n");
x--;
y *= x;
z %= x;
System.out.println("And now x = "+x+", y = "+y+", z = "+z+ "\n");
System.exit(0);
}
}
 2003 Prentice Hall, Inc. All rights reserved (Modified) .