Control structures: if-else statements and switch statements 2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in JAVA: V
2003 Prentice Hall, Inc. All rights reserved (Modified). 2 Relational Operators (revisited) Not Equal to!= Equal to== Less than or equal to<= Greater than or equal to>= Less than< Greater than> MeaningOperator
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 }
2000 Prentice Hall, Inc. All rights reserved. (modified) 5 // 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) 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
2003 Prentice Hall, Inc. All rights reserved (Modified). 7 Nested if-else // ages import javax.swing.JOptionPane; 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); // Convert the string into an int value System.out.println(" Your age is " + age + "."); /* 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). 8 Nested if-else // grades: example #2 import javax.swing.JOptionPane; 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). 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; case value2: action(s); break; … default: actions(s); break; } keyword switch could use more than one case; if the same actions are required expression can be a variable or a more complicated expression 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). 11 switch Multiple-Selection FlowChart Case a action(s) True Case a break Case b action(s) break Case b Default action(s) Default false True
2003 Prentice Hall, Inc. All rights reserved (Modified). 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). 13 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). 14 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). 15 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). 16 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). 17 The boolean Type and Operators boolean lightsOn = true; boolean lightsOn = false; boolean b = (1 > 2); && (and) (1 < x) && (x < 100) || (or) (1 < x) || (x < 100) ! (not)!(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 ! Operand!Operand true false false true
2003 Prentice Hall, Inc. All rights reserved (Modified). 21 Truth Table for Operator && Operand1Operand2 Operand1 && Operand2 falsefalsefalse falsetruefalse truefalsefalse truetruetrue
2003 Prentice Hall, Inc. All rights reserved (Modified). 22 Truth Table for Operator || Operand1Operand2Operand1 || Operand2 falsefalsefalse falsetruetrue truefalsetrue truetruetrue
2003 Prentice Hall, Inc. All rights reserved (Modified). 23 Increment and Decrement Operators
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.
2003 Prentice Hall, Inc. All rights reserved (Modified). 26 Increment and Decrement Operators, cont. F Using increment and decrement operators makes expressions short F but it also makes them complex and difficult to read. F 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; 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); } x = 10, y = 5, z = 3 Now x = 11, y = 16, z = 33 And now x = 10, y = 160, z = 3 Press any key to continue...