Multiple if-else boolean Data Chapter 5 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010 1 1
Programs Program 6 is being graded. Program 7 is on my website. Bonus point for evaluation. 2
Topics Multiple if-else(5.3) Boolean Data (5.6) 3 3 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010 3 3
Multiple Outcomes if-else can produce two possible outcomes. One outcome for true Another for false condition Sometimes there can be several possible outcomes.
Example Course Description Write a program to accept a course number then print the description for the course.
import java.util.Scanner; //Outputs a course description for a course number public class CourseDescription { public static void main(String[] args) { //Input the course number Scanner scan = new Scanner(System.in); System.out.print("Enter Course Number:"); String number = scan.next(); //Output correct description if(number.equals("CS119")) System.out.println("Intro to Java"); else if(number.equals("CS115")) System.out.println("Intro to C"); else if(number.equals("CS117")) System.out.println("Intro to C++"); else System.out.println("Number not found."); scan.close(); }
Movie Ticket Example Move tickets sell at $6 for children under 14, $12 for adults, and $8 for seniors over 55. Three outcomes Can use an a serious of if-statements in a chain to determine the price, given the age.
import java.util.Scanner; import java.text.DecimalFormat; //Determine movie price based on age public class Movie{ public static void main(String []args){ //Input movie-goer's age Scanner scan = new Scanner(System.in); System.out.print("What is your age?"); int age = scan.nextInt(); //Decide price, based on age. double price = 0.0; if(age <= 14) price = 6.00; else if(age < 55) price = 12.00; else price = 8.00; DecimalFormat formatter = new DecimalFormat("$0.00"); System.out.println(formatter.format(price) + " please."); }
Boolean Variables Skip this Spring ‘16
Boolean Variables boolean is a primitive type. boolean variables can store either true or false. Can use to flag condition. Example: boolean icyRoads = true; if(icyRoads) System.out.println(“Stay home.”); else System.out.println(“Drive on.”);
Boolean data field in Class public class AutoRepair{ private String name; private String make; private String model; private boolean done; . . .
What is the value in y? int y, x = 5; boolean flag = true; if (x > 10 || x < 2) y = 1; else if(flag) y = 2; else if(x > -2) y = 3; else y = 4;
Participation Write a program to accept an integer for placement in a hog show at the fair. Use a multiple if-else statement to output the ribbon color for the placement “Blue” “Red” “White” Any other number is “No ribbon”