Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
AP/CS A Lab 4: if else University of Washington, AP/CS A Lab 4: if else University of Washington, AP/CS A Lab 4: if else Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp. lab document created by Marty Stepp, Stuart Reges and Whitaker Brand Today's lab Goals for this lab: use if, else if, and else to have different branches of execution Where you see this icon, you can click it to check the problem in Practice-It! Conditional Statements Conditional statements lets your program choose to do different things based on the results of tests, which evaluate certain parts of a program. There are 3 structures that we can use: if statements else statements else if statements if statements if statements are composed of a test, and some code to execute if that test is true (ex. 2 + 2 = 4 is true). if (test) { statement(s); // executes if test is true } System.out.println("yay!") // prints yay, business as usual outside the if statement Example: if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); // perform this code is gpa >= 2.0 } Exercise : if statements What does the following code output? 1 2 3 4 5 x = 5; if (x < 0) { System.out.println("inside if branch!"); } System.out.println("outside if branch!"); Output: outside if branch! Exercise : if statements What does the following code execute? 1 2 3 4 5 x = -2; if (x < 0) { System.out.println("inside if branch!"); } System.out.println("outside if branch!"); Output: inside if branch! outside if branch! Exercise : if statements What does the following code execute? 1 2 3 4 5 6 7 8 x = -2; if (x < 0) { System.out.println("inside if branch!"); } if (x < -1) { System.out.println("inside this branch!"); } System.out.println("outside if branch!"); Output: inside if branch! inside this branch! outside if branch! Note: it's possible for any if statement to execute, or not. If you have a couple if statements next to each other, 0 of them, 1 of them, or both of them could execute. if/else statements if/else statements are statements that include two branches, one of which is always executed. They allow us to control our program's behavior when the if statement's test evaluates to false. if (test) { statement } else { // implicitly, test is false statement } Example: if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); // perform this code is gpa >= 2.0 } else { System.out.println("Please apply again soon."); // perform this code is gpa < 2.0 } Exercise : if-else practice What does the following program output? 1 2 3 4 5 6 7 8 9 public static void main(String[] args) { int x = 5; if (x < 5) { System.out.println("abc"); } else { System.out.println("def"); } System.out.println("ghi"); } Output: def ghi Exercise : if-else practice What does the following program output? 1 2 3 4 5 6 7 8 9 public static void main(String[] args) { int x = 2; if (x < 5) { System.out.println("abc"); } else { System.out.println("def"); } System.out.println("ghi"); } Output: abc ghi Note: With if-else structures, exactly one branch will execute. It is impossible for neither the if branch or the else branch to execute. It is also impossible for both to execute. nested if/else statements Nested if/else statements allow you to write code that executes if its test is met, but only in the case that an if statement before it has already evaluated to false. if (test1) { statement // executes if test1 == true } else if (test2) { statement // executes if test1 -= false AND test 2 == true } Example: if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); // perform this code is gpa >= 2.0 } else if (gpa < 0.7) System.out.println(":*("); // perform this code when gpa < 2.0 and < 0.7 } Exercise : if/else mystery public static void mystery(int n) { System.out.print(n + " "); if (n > 10) { n = n / 2; } else { n = n + 7; } if (n * 2 < 25) { n = n + 10; } System.out.println(n); } Fill in the boxes with the output produced by each of the method calls. mystery(40); 40 20 mystery(0); 0 17 mystery(12); 12 16 mystery(20); 20 20 Exercise : if/else mystery public static void mystery2(int a, int b) { if (a < b) { a = a * 2; } if (a > b) { a = a - 10; } else { b++; } System.out.println(a + " " + b); } Fill in the boxes with the output produced by each of the method calls. mystery2(10, 3); 0 3 mystery2(6, 6); 6 7 mystery2(3, 4); -4 4 mystery2(4, 20); 8 21 Exercise : if/else mystery public static void mystery3(int x, int y) { int z = 4; if (z <= x) { z = x + 1; } else { z = z + 9; } if (z <= y) { y++; } System.out.println(z + " " + y); } Fill in the boxes with the output produced by each of the method calls. mystery3(3, 20); 13 21 mystery3(4, 5); 5 6 mystery3(5, 5); 6 5 mystery3(6, 10); 7 11 Exercise : Syntax errors The following Java program has 7 errors. Can you find all of them? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class IfOops { public static void main(String[] args) { int a = 7, b = 42; minimum(a, b); if {smaller = a} { System.out.println("a is the smallest!"); } } public static void minimum(int a, int b) { // returns which int is smaller if (a < b) { int smaller = a; } else (a => b) { int smaller = b; } return int smaller; } } Copy and paste the code into jGrasp and see if you can fix the errors. Exercise - answer line 5: if statement should use () parentheses, not {} brackets line 5: = should be == line 5: smaller is out of scope here line 10: void should be int line 13: => should be >= (or better yet, no if test is needed) line 16: should not write variable's type of int when returning it line 16: int smaller is out of scope here (declare outside if or return directly) Exercise - Corrected version public class IfOops { public static void main(String[] args) { int a = 7, b = 42; int smaller = minimum(a, b); if (smaller = = a ) { System.out.println("a is the smallest!"); } } public static void int minimum(int a, int b) { // returns which int is smaller int smaller; if (a < b) { int smaller = a; } else if (a >= b) { int smaller = b; } return int smaller; } } Exercise : seeMovie You're thinking about going with your friends to a movie. Write a Java method seeMovie that accepts two parameters: the cost of a ticket in dollars, and the rating number of stars the movie received out of 5. The method should print how interested you are (very, sort-of, or not). Use the following criteria: You like bargains. Any movie that costs less than $5.00 is one that you want to see very much. You dislike expensive movies. You are not interested in seeing any movie that costs $12.00 or more, unless it got 5 stars (and even then, you are only sort-of interested). You like quality. You are very interested in seeing 5-star movies that cost under $12.00. You are sort-of interested in seeing movies costing between $5.00 - $11.99 that also got between 2-4 stars inclusive. You are not interested in seeing any other movies not described previously. Exercise : AgeCheck Copy/paste and save the following program in jGRASP, then see the instructions on the next slide. public class AgeCheck { public static void main(String[] args) { int myAge = 19; // I am 19; let me see if I can drive message(myAge); } // Displays message about driving to user based on given age public static void message(int age) { if (myAge >= 16) { System.out.println("I'm old enough to drive!"); } if (myAge <= 16) { System.out.println("Not old enough yet... :*("); } } } Exercise - things to fix The program has a few syntax errors. Fix them until it compiles. The code has a logic problem. (For some value(s), it prints the wrong answer.) Find any such problems and fix them. (You may need to run the program a few times and try different values to see which ones fail.) The program uses if and else in a clumsy way. Improve the style of the code. Exercise - answer The following is a corrected version of the program: public class AgeCheck { public static void main(String[] args) { int myAge = 19; // I am 19; let me see if I can drive message(myAge); } // Displays a message about driving to user based on given age public static void message(int age) { if ( age >= 16) { System.out.println("I'm old enough to drive!"); } else { System.out.println("Not old enough yet... :*("); } } } Exercise : numUnique Write a method named numUnique that accepts three integers as parameters and that returns the number of unique integers among the three. For example, the call numUnique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call numUnique(6, 7, 6) would return 2 because there are only 2 unique numbers among the three parameters: 6 and 7. Compare your solution to your neighbors'. Did you all solve it the same way? (Try solving this problem in Practice-It by clicking the icon above.) Exercise : pay Write a method named pay that accepts two parameters: a real number for a TA's salary, and an integer for the number of hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive "overtime" pay of 1 ½ normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0. if/else factoring Recall that with if/else, exactly 1 branch executes. This make a new kind of redundancy possible! if (x < 30) { a = 2; x++; System.out.println("CSE 142 TAs are awesome! " + x); } else { a = 2; x--; System.out.println("CSE 142 TAs are awesome! " + x); } Because the red code will happen no matter what (in the if and the else case), it can be factored out: a = 2; if (x < 30) { x++; } else { x--; } System.out.println("CSE 142 TAs are awesome! " + x); Exercise : if/else Factoring Download the following program FactorExample.java to your machine and open it with jGrasp. The program's method has a few issues with external correctness and redundancy. Fix the code, and factor the method, restructuring the code to eliminate unnecessary statements while retaining the same behavior. This might involve changing conditional statements (ex. changing an if to an else if). (When fixed,) running the program should produce the following output: continued on the next slide... Exercise : if/else Factoring Expected Output I'm valedictorian for this class! Woo hoo! I made the dean's list for this class! I received 5 credits for this class. I made the dean's list for this class! I received 5 credits for this class. I received 5 credits for this class. Uh-oh..I probably should have studied a little more. I received 0 credits for this class. Uh-oh..I probably should have studied a little more. I received 5 credits for this class. Exercise : if/else Factoring public static void factoring(double gpa) { int credits = 5; // since we want credits = 5 in all cases except gpa <= 0.7 if (gpa == 4.0) { credits = 5; System.out.println("I'm valedictorian for this class! Woo hoo!"); System.out.println("I made the dean's list for this class!"); } else if (gpa >= 3.5) { // we want the same behavior for all gpa >= 3.5 cases (4.0 or not) credits = 5; System.out.println("I made the dean's list for this class!"); } else { credits = 5; } else if (gpa < 1.5) { // gpa can be < 1.5, >= 3.5, or neither System.out.println("Uh-oh..I probably should have studied a little more."); } if (gpa <= 0.7) { System.out.println("Uh-oh..I probably should have studied a little more."); credits = 0; } System.out.println("I received " + credits + " credits for this class."); System.out.println(); } Exercise : season Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31. If the date falls between 12/16 and 3/15, you should return "Winter". If the date falls between 3/16 and 6/15, you should return "Spring". If the date falls between 6/16 and 9/15, you should return "Summer". And if the date falls between 9/16 and 12/15, you should return "Fall". Try solving this problem in Practice-It! using the link above. Exercise : before Write a method before that takes as parameters two month/day combinations and that returns whether or not the first date comes before the second date (true if the first month/day comes before the second month/day, false if it does not). The method will take four integers as parameters that represent the two month/day combinations. The first integer in each pair represents the month and will be a value between 1 and 12 (1 for January, 2 for February, etc, up to 12 for December). The second integer in each pair represents the day of the month (a value between 1 and 31). One date is considered to come before another if it comes earlier in the year. Solve this problem in Practice-It by clicking on the check-mark above.