Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CSE 142 Lab 1: Static Methods; Expressions and Variables University of Washington, CSE 142 Lab 1: Static Methods; Expressions and Variables University of Washington, CSE 142 Lab 1: Static Methods; Expressions and Variables Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp. lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin Basic lab instructions Talk to your classmates for help. You can even work on the lab with a partner if you like. 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 many problems as you can within the allotted time. You don't need to keep working on these exercises after you leave the lab. Feel free to complete problems in any order. Before you leave today, make sure to check in with one of the TAs in the lab to get credit for your work. Today's lab Goals for today: meet some of your classmates learn about the jGRASP editor software gain familiarity with syntax errors and debugging learn about various useful CSE 142 online tools and resources practice using static methods to capture structure and redundancy (Ch. 1) use expressions and variables for numeric computations (Ch. 2) trace and write for loops for repeating lines of code Exercise : Meet your neighbors In this exercise, you will meet your neighbors and write a program that displays facts about them. Create a complete Java program in a class named Neighbors. Introduce yourself to two people around you (get up to do so if you have no immediate neighbors). Ask them for their full name, including their middle initial. Make sure you know how to spell their name correctly! Ask them for an interesting fact about themselves. Your program should output the name and interesting fact of two of your neighbors. You may put all of your code in the main method. Your output should look like the following: Talib K. Greene's mother is an English professor in New York. Jermaine L. Cole was born in Germany. Exercise : Practice indentation Programs should be indented properly to make them easier to read: { brace → increase indent of following lines by one tab } brace → decrease indent of that line and following lines by one tab Example: public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); System.out.println("How are you?"); } } Make sure that your Neighbors program has good indentation. continued on the next slide... Exercise : Practice indentation, cont'd Our Indenter Tool web page can fix a program's indentation. In this exercise, we will use the Indenter Tool to fix the following program that has poor indentation. Download it and open it in jGRASP: Icky.java continued on the next slide... Exercise : Practice indentation, cont'd Go to the CSE 142 Labs page. Under Lab 1, click Indenter Tool. Copy/paste the Icky.java code into the Indenter's text box. Click Fix Indentation. (Indent by 3 spaces.) Paste the properly indented code in the box below. public class Icky { public static void main(String[] args) { System.out.println("Well-indented programs"); System.out.println("look much better."); System.out.println("Please fix me"); System.out.println("so I look nicer"); } } Exercise : Syntax errors The following program contains 11 errors! Work with a partner to find them all. You may want to run the program and jGRASP and see what kinds of error messages are shown for each kind of mistake. 1 2 3 4 5 6 7 8 9 public class Tricky public static main(String args) { System.out.println(Hello world); system.out.Pritnln("Do you like this program"?); System.out.println() System.println("I wrote it myself."; { } Once you think you've found the errors, create/compile/run a corrected version of this program. answer on next slide... Exercise - answer line 1: missing { after Tricky line 2: missing void before main line 2: missing [] after String line 3: missing " marks around Hello world line 4: system should be System (uppercase S) line 4: Pritnln should be println (lowercase P and fixed spelling) line 4: ? should be before " line 5: missing semicolon after () line 7: missing ) after " line 8: System.println should be System.out.println line 8: { should be } Exercise - corrected version Here is a corrected version of the program: public class Tricky { public static void main(String [] args) { System.out.println( "Hello world "); System.out. println("Do you like this program ?"); System.out.println() ; System. out.println("I wrote it myself." ); } } Static methods Recall the syntax for writing a static method. Methods are useful for representing a program's structure and capturing common code to avoid redundancy: public static void name() { statements; } Example: public static void song() { System.out.println("This is the song that never ends,"); System.out.println("Yes, it goes on and on, my friends."); } Exercise : FightSong Go, team, go! You can do it. Go, team, go! You can do it. You're the best, In the West. Go, team, go! You can do it. Go, team, go! You can do it. You're the best, in the West. Go, team, go! You can do it. Go, team, go! You can do it. The following program produces the output at left, but it has poor structure and redundancy. Download it and open it in jGRASP, then add at least two static methods. FightSong.java continued on the next slide... Exercise : FightSong, cont'd Go, team, go! You can do it. Go, team, go! You can do it. You're the best, In the West. Go, team, go! You can do it. Go, team, go! You can do it. You're the best, In the West. Go, team, go! You can do it. Go, team, go! You can do it. Did you choose your methods well? Avoid the following pitfalls: Does the same println statement occur more than once in your code? Are there any println statements in the main method? Is your main method a good summary of the overall program? (If main is only 1-2 lines long, it is not a good summary.) Do you have any patterns of method calls that are repeated in the code? Compare your method choice with your neighbor's. Discuss any different decisions you made and ask a TA if you have questions about them. Exercise : Practice verifying output Your homework must match expected output exactly. You can use our Output Comparison Tool web page to check your output. In this exercise, we will check whether a program produces correct output. Download the program and open it in your jGRASP editor. WrongOutput.java continued on the next slide... Exercise : Practice verifying output, cont'd Go to the CSE 142 Labs page. Under Lab 1, click Output Comparison Tool. In the Output Comparison page, select WrongOutput.java from the list. Run jGRASP and use it to edit WrongOutput.java. Copy/paste the program's output from jGRASP's console into the "Actual Output" box of the Output Comparison web page. Click Compare on the page. (Also click Add Line Numbers on the web page.) Which output line number does not match? 4 What should be the output for that line? "Four score and seven years ago, Which expected blank line number is missing? 8 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 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 + 8 / 4 4 3 * 4 + 15 / 2 19 -(1 + 2 * 3 + (1 + 2) * 3) -16 42 % 5 + 16 % 3 3 2.5 * 2 + 17 / 4 9.0 4.5 / 3 / 2 + 1 1.75 Exercise : More expressions (2.1) Write the results of each of the following expressions. 5 * 6 / 4 % 3 - 23 / (14 % 6) -10 30 % 9 + 5 % 8 - 11 % 4 % 2 7 1 + 9 / 2 * 2.0 9.0 46 / 3 / 2.0 / 3 * 4/5 2.0 50 / 9 / 2.0 + 200 / 10 / (5.0 / 2) 10.5 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 = 499.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 : 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 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 <= 10; i++) { System.out.println("We're number one!"); } 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 : 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 : 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 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 : Lanterns Write a complete program named Lanterns that produces the following output. Use static methods to capture structure and remove redundancy. (Check your output on the Comparison Tool.) ***** ********* ************* ***** ********* ************* * | | | | | * ************* ***** ********* ************* ***** ********* ************* ***** * | | | | | * * | | | | | * ***** ***** Exercise : Spell your name Write a complete program that outputs your name in giant letters like the following: M M IIIII SSSSS PPPPPP MM MM I S S P P M M M M I S P P M M M I SSSSS PPPPPP M M I S P M M I S S P M M IIIII SSSSS P The giant letters should flow vertically. Use methods to avoid redundancy when the same giant letter appears multiple times in your name. (Use only the material from Chapter 1.) 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!