Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
common/conf common/conf CSE 142 Lab 2: Expressions, Variables, and Loops University of Washington, CSE 142 Lab 2: Expressions, Variables, and Loops University of Washington, CSE 142 Lab 2: Expressions, Variables, and Loops 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 Basic lab instructions Mouse over highlighted words if you're not sure what they mean! Talk to your classmates for help. You may want to bring your textbook to future labs to look up syntax and examples. Stuck? Confused? Have a question? Ask a TA for help, or look at the book or past lecture slides. Complete as much of the lab as you can within the allotted time. You don't need to keep working on these exercises after you leave. Feel free to complete problems in any order. Make sure you've signed in on the sign-in sheet before you leave! Today's lab Goals for today: write and evaluate expressions to compute numeric values use variables to store results of a computation into memory trace and write for loops for repeating lines of code draw patterned figures of text using loops Operators Java has operators for the standard mathematical operations. Note that + works a little differently depending on the type of the operands. Operator Description + Addition for ints and doubles, concatenation for Strings - Subtraction for ints and doubles, doesn't compile for Strings * Multiplication for ints and doubles, doesn't compile for Strings / Division for ints and doubles, doesn't compile for Strings Note that ints will follow integer (truncated) division rules % Modulus for ints and doubles, doesn't compile for Strings Precedence Generally speaking, Java tries to evaluate your expression from left to right. However, some operations happen before others. Java follows a set of rules of precedence that should be familiar from Algebra class, abbreviated PEMDAS. Java doesn't have an exponent operator, but it does have the modulus (%) operator, so the mnemonic becomes: PMMDAS P :: first, evaluate expressions surrounded by Parentheses () MMD :: then, perform all Multiplication *, Modulus %, and Division / operations AS :: finally, go through and perform the Addition +, and Subtraction - Expressions Recall that Java has expressions to represent math and other computations. Expressions may use operators, which are evaluated according to rules of precedence. Every expression produces a value of a given type. Type Description Expression Example Result int integers (up to 231 - 1) 3 + 4 * 5 23 double real numbers (up to 10308) 3.0 / 2.0 + 4.1 5.6 String text characters "hi" + (1 + 1) + "u" "hi2u" Exercise : Expressions (2.1) Write the results of each of the following expressions. If you're stuck, ask a TA or neighbor. 12 / 5 2 12.0 / 5 2.4 12 / 5 + 8 / 4 4 3 * 4 + 15 / 2 19 42 % 5 + 3 % 16*** 5 ***Hint: Suppose you have 3 apples, and you distribute them among 16 people so that everyone gets the same number of (whole) apples. How many (whole) apples does each person get? How many apples do you have left over? String Concatenation The + operator does addition on numbers, but on Strings, it instead appends the two Strings together. System.out.println("Hello, World!"); // prints: Hello, World! System.out.println("Hello, " + "World!"); // prints: Hello, World! System.out.println("You " + "can" + " add" + "many" + " Strings together"); // prints: You can addmany Strings together System.out.println("Numbers " + 2 + "!"); // prints: Numbers 2! Note that only the whitespace inside the quotation marks is preserved. Using quotation marks tells Java to keep track of every character from the opening " to the closing ", including the whitespaces like spaces, tabs, and newlines. Outside the quotes, we're back in the Java program itself, where Java doesn't notice or care about the newline we've used to format the long line of source code. String Concatenation with numbers We do String concatenation instead of addition if either of the operands are Strings. We only add the numbers together if both of them are numbers (not Strings). Java keeps track of the type of pieces of data in your program. It treats "4" (a String) differently than it treats 4 (a numerical value). Having the distinction is crucial for some tasks: if the computer always treated numerical Strings as numbers, then we wouldn't have a way to prepend an area code to the beginning of a phone number. // All are using the + on a String -- all perform concatenation. System.out.println("1" + "2"); // prints 12 System.out.println("1" + 2); // same, prints 12 System.out.println(1 + "2"); // same, prints 12 // Since both operators here are numbers, we do addition: System.out.println(1 + 2); // does addition before printing -- prints 3 Note: Even though the + operator works differently on Strings, it still follows the same precedence rules. Exercise : More expressions (2.1) Write the results of each of the following expressions. Some of these expressions include String concatenation. When the result of the expression evaluates to a String, put "quotation marks" around the result: "x" + 2 "x2" // Add the other quote to get the correct answer 2 + 6 + "cse 142" "8cse 142" "cse 142" + 2 + 6 "cse 14226" 1 + 9 / 2 * 2.0 9.0 46 / 3 / 2.0 / 3 * 4/5 2.0 jGRASP Interactions Pane jGRASP has a useful feature called the Interactions Pane that allows you to type in Java expressions or statements one at a time and instantly see their results. To use it, run jGRASP and then click the "Interactions" tab near the bottom. continued on the next slide... Exercise : Using jGRASP Interactions Pane In this exercise, you'll use the Interactions Pane to quickly discover the result of some expressions that would be difficult to evaluate by hand. Copy/paste each expression below into the Interactions Pane to evaluate it, then input the answer into this slide. 123 * 456 - 789 55299 3.14 + 1.59 * 2.65 7.3535 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 1024 2 + 2 + "xyz" + 3 + 3 "4xyz33" (For the last expression, the Interactions Pane doesn't put "" quotes around Strings when displaying results, so you must add those yourself if needed. For example, if the Interactions Pane gives you a result of abc123, it should be written here as "abc123".) Variables Recall that you can use a variable to store the results of an expression in memory and use them later in the program. type name; // declare name = value or expression; // assign a value ... type name = value or expression; // declare-and-initialize together Examples: double iPhonePrice; iPhonePrice = 299.95; int siblings = 3; System.out.println("I have " + siblings + " brothers/sisters."); Exercise : Variable declaration syntax Which of the following choices is the correct syntax for declaring a real number variable named grade and initializing its value to 4.0? grade : 4.0; int grade = 4.0; 4.0 = grade; grade = 4.0; double grade = 4.0; grade = double 4.0; Exercise : Variable assignment syntax Suppose you have a variable named grade, set to 1.6: double grade = 1.6; // uh-oh Suppose later in the program's code, we want to change the value of grade to 4.0. Which is the correct syntax to do this? grade : 4.0; double grade = 4.0; grade = 4.0; 4.0 = grade; set grade = 4.0; Exercise : Variable mutation Suppose you have a variable named balance, set to 463.23: double balance = 463.23 Suppose later in the program's code, we want to add 5 to the account balance. Which is a correct statement to do this? balance + 5; balance = 5; balance = balance + 5; 5 + balance = balance; balance <-- 5; Exercise : a, b, and c What are the values of a, b, and c after the following statements? Write your answers in the boxes on the right. int a = 5; int b = 10; int c = b; a = a + 1; // a? 6 b = b - 1; // b? 9 c = c + a; // c? 16 Exercise : i, j, and k What are the values of i, j, and k after the following statements? int i = 2; int j = 3; int k = 4; int x = i + j + k; i = x - i - j; // i? 4 j = x - j - k; // j? 2 k = x - i - k; // k? 1 print vs println There is a method called System.out.print that is similar to System.out.println. They are different in that print doesn't add a "new line" (line break, '\n') character to the end of your output. System.out.print("hello,"); System.out.print("helloooo"); // prints: hello,helloooo System.out.println("hello,"); System.out.println("helloooo"); // prints: // hello, // helloooo Every time you call System.out.println() Java will add a "new line" character to your output. for loops A for loop repeats a group of statements a given number of times. for (initialization; test; update) { statement(s) to repeat; } Example: for (int i = 1; i <= 3; i++) { System.out.println("We're number one!"); } System.out.println("/cheering"); Output: We're number one! We're number one! We're number one! /cheering for loops for (initialization; test; update) { statement(s) to repeat; } for (int i = 1; i <= 3; i++) { System.out.println("We're number one!"); } System.out.println("/cheering"); The for loop keeps executing the println as long as the test condition is met: initialization :: int i = 1; :: start a counter at 1 test :: i <= 3; :: continue as long as the counter i is less than 3 execute the statements :: { System.out.println("We're number one!"); } update :: i++ :: add 1 to the counter go back to step 2 and check the test condition again: i is 1 bigger than it was last time through the loop Once the test isn't true anymore, Java exits the for loop :: System.out.println("/cheering"); Exercise : for loop repeating For each of the following for loops, write the output that would be produced by executing them. for(int i = 1; i <= 3; i++) { System.out.print("*"); } output: *** for(int i = 1; i <= 4; i++) { System.out.print("!-!"); } output: !-!!-!!-!!-! // Note the number/String concatenation here in the print(). // i is an int variable that holds onto a numerical value. // // For which numerical values does i hold as the for loop executes? for(int i = 1; i <= 5; i++) { System.out.print(i + "~"); } output: 1~2~3~4~5~ Exercise : simple for loop Copy/paste the following code into jGRASP. public class Count2 { public static void main(String[] args) { for ( fill me in! ) { System.out.println( fill me in! ); } } } Modify the code to produce the following output: 2 times 1 = 2 2 times 2 = 4 2 times 3 = 6 2 times 4 = 8 Exercise : Verify solution in Practice-It! Our Practice-It! system lets you solve Java problems online. Go to the Practice-It! web site. Create an account if you don't have one, and log in. Under the "CS1 Labs", "Lab 2" category, select the "simple for loop" problem. (direct link) Copy/paste your program from jGRASP into Practice-It, and submit. If it does not pass the test, modify your code and re-submit it. Exercise : What's the output? What output is produced by the following Java program? Write the output in the box on the right side. public class OddStuff { public static void main(String[] args) { int number = 32; for (int count = 1; count <= number; count++) { System.out.println(number); number = number / 2; } } } Output: 32 16 8 4 Exercise : What's the output? What output is produced by the following Java method? public static void stars() { for (int i = 1; i <= 10; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } for (int j = 1; j <= 20 - 2 * i; j++) { System.out.print(" "); } for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); } } (Try to figure it out without running the code... If you give up, copy and paste it into jGrasp and run it!) Hint: Think of each inner loop from 1 to X as a loop that prints X copies of the given character. Exercise - answer Answer: * * ** ** *** *** **** **** ***** ***** ****** ****** ******* ******* ******** ******** ********* ********* ******************** Exercise : for loop practice Copy and paste the following code into jGrasp. public class Triangle { public static void main(String[] args) { for (int line = 1; line <= 4; line++) { for (int stars = 1; stars <= expression ; stars++) { System.out.print("*"); } System.out.println(); } } } continued on the next slide... Exercise - fill in a table We want to produce the following output: ******* ***** *** * Fill in the table below indicating how many stars appear on each line of output. Line Stars 1 7 2 5 3 3 4 1 Exercise - complete the expression We need an expression for the number of stars on each line of this form: multiplier * line + constant First pick a multiplier. Looking at the table, the line numbers go up by 1 each time, and the number of stars changes by how much each time? -2 Now pick a constant. Look at the table to see how many stars are on line 1. Given your multiplier, what constant do you need to use in the expression to get that number of stars for line 1? 9 Using your multiplier and constant, fill in the expression for this line of code in jGRASP: for (int stars = 1; stars <= expression ; stars++) { Your program should now produce the correct output. You can verify with the Output Comparison Tool. Exercise : Number lines, part 1 Write some nested for loops to produce the following output: 000111222333444555666777888999 000111222333444555666777888999 000111222333444555666777888999 You can use the Output Comparison Tool to check your work. Exercise : Number lines, part 2 Modify the previous code to have it do something a little different: 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 99999888887777766666555554444433333222221111100000 You can use the Output Comparison Tool to check your work. Exercise : Number lines, part 3 Modify the code to have it produce this output: 999999999888888887777777666666555554444333221 999999999888888887777777666666555554444333221 999999999888888887777777666666555554444333221 999999999888888887777777666666555554444333221 You can use the Output Comparison Tool to check your work. Exercise : printing a design Write a program to produce the following output using nested for loops. Use a table to help you figure out the patterns of characters on each line. -----1----- ----333---- ---55555--- --7777777-- -999999999- Line Dashes Numbers 1 5 1 2 4 3 3 3 5 4 2 7 5 1 9 dashes expression -1 * line + 6 numbers expression 2 * line + -1 Test your loop expressions in Practice-It! using the checkmark icon above. Use your expressions in the loop tests of the inner loops of your code. Exercise : SlashFigure Write a Java program in a class named SlashFigure to produce the following output with nested for loops. Use a loop table if necessary to figure out the expressions. !!!!!!!!!!!!!!!!!!!!!! \\!!!!!!!!!!!!!!!!!!// \\\\!!!!!!!!!!!!!!//// \\\\\\!!!!!!!!!!////// \\\\\\\\!!!!!!//////// \\\\\\\\\\!!////////// Line \ ! / 1 0 22 0 2 2 18 2 3 4 14 4 4 6 10 6 5 8 6 8 6 10 2 10 multiplier 2 -4 2 shift -2 26 -2 Test your code in Practice-It! or the Output Comparison Tool. Exercise : SlashFigure2 Make a table of "\", "!", and "/" counts in the size 4 figure. Then, write a for loop to produce the size 4 figure. Finally, compare the loop tests for the size 4 and 7 figures, and write a for loop with a class constant that will produce a figure of any SIZE. size 4 size 7 !!!!!!!!!!!!!! \\!!!!!!!!!!// \\\\!!!!!!//// \\\\\\!!////// !!!!!!!!!!!!!!!!!!!!!!!!!! \\!!!!!!!!!!!!!!!!!!!!!!// \\\\!!!!!!!!!!!!!!!!!!//// \\\\\\!!!!!!!!!!!!!!////// \\\\\\\\!!!!!!!!!!//////// \\\\\\\\\\!!!!!!////////// \\\\\\\\\\\\!!//////////// Test your code in the Output Comparison Tool or in PracticeIt! Exercise : ComputePay The following program redundantly repeats the same expressions many times. Download it and open it in jGRASP, then modify the program to remove the redundancy using variables. Use an appropriate type for each variable. ComputePay.java The program's output should be the same after your modifications. No expression should be computed more than once in the code. Exercise : Syntax errors The following program contains 9 mistakes! What are they? Copy and paste the following code into jGRASP and correct the various mistakes. The answer is on the next 2 slides if you need some help. 1 2 3 4 5 6 7 8 9 10 11 12 13 public class Oops { public static void main(String[] args) { int x; System.out.println("x is" x); int x = 15.2; // set x to 15.2 System.out.println("x is now + x"); int y; // set y to 1 more than x y = int x + 1; System.out.println("x and y are " + x + and + y); } } answer on next slide... Exercise - answer line 4: missing + between "x is" and x line 4: cannot print the value of x before assigning it a value line 6: cannot assign 15.2 into a variable of type int line 6: should not redeclare the variable's type line 7: " mark should be between now and + line 10: should not write the word int here line 10: variable y should be same type as x line 10: does not properly set y to be 1 more than x (should not write the word int here) line 11: and should be in quotes with surrounding spaces Exercise - corrected version Here is a corrected version of the program: public class Oops { public static void main(String[] args) { double x = 0.0; System.out.println("x is" + x); x = 15.2; // set x to 15.2 System.out.println("x is now " + x); double y; // set y to 1 more than x y = x + 1; System.out.println("x and y are " + x + " and " + y); } } Exercise : Equation Suppose you have a real number variable x. Write a Java expression that computes a variable named y storing the following value: y = 12.3x4 - 9.1x3 + 19.3x2 - 4.6x + 34.2 (We haven't learned a way to do exponents yet, but you can simulate them using several multiplications.) Use the example program on the next slide to test your code. Exercise - Example code Copy/paste this program into jGRASP to test your solution. // expected output: // y is 7043.7 public class EquationY { public static void main(String[] args) { double x = 5; double y = put your expression for y here ; System.out.println("y is " + y); } } (answer on next slide) Exercise - answer double y = 12.3*x*x*x*x - 9.1*x*x*x + 19.3*x*x - 4.6*x + 34.2; If you want an added challenge, try to come up with a way to compute the above value while using the * operator no more than 4 times. (click Next → for answer) double y = (((12.3 * x - 9.1) * x + 19.3) * x - 4.6) * x + 34.2; Exercise : Birthday variables Create a complete Java program in a class named Bday that declares four variables and assigns appropriate values to them. your birthday month (1-12) your birthday day (1-31) the birthday month of another student sitting near you today (1-12) the birthday day of that same student near you (1-31) Ask your neighbor for their name and for the proper numbers to store in the variables for his/her birthday. Then produce output in this format using your four variables: My birthday is 9/19, and Suzy's is 6/14. If you finish them all... If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook. You can view an exercise, type a solution, and submit it to see if you have solved it correctly. Choose some problems from the book and try to solve them!