Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Chapter 1: Introduction to Java Programming  previous  next  Weeks 1 and 2:  Introduction to Java Programming  Objectives Cover the syllabus. Browse the course's web pages at http://www.cs.utsa.edu/~cs1083. See an example of an algorithm. Edit, compile and execute simple Java programs. Use System.out.println and System.out.print. Use static methods for subtasks of a program. Become familiar with Blackboard for taking quizzes and submitting labs. Assignments Complete zyBook Chapters 1 and 2 participation and challenge activities before each class and before the Wednesday deadline of respective week Chapter  1 zyLab activities due beginning of Week 2 and Chapter 2  zyLab activities due beginning of Week 3 Introduce Project 1 Outline Setup Algorithms Your First Lab Writing Simple Programs Static Methods Summary of Syntax Setup Logging in for the First Time If you registered this course, you have your own account to access the computer in classroom and the CS Main labs. Your account is your UTSA id abc123, and your password will be given in the first lecture. When you log in for the first time you will be prompted to change your password. Passwords must be at least 14 characters in length. It is recommended that you use the same password as you use to access your UTSA account. This will make it easier for you to remember. When the class is over, be sure to exit VDI by clicking on the X at the top of the screen. Setting up ClassQue Find the lecture notes and select Weeks 1 and 2 That will get you to this page. Go to the classque setup page: http://classque.cs.utsa.edu/classque/utsa/student.html Find your course in the table and run the setup link: click on it to download it then run it This will put a ClassQue icon on your desktop Double click on this icon at the start of class to register your attendance. Setting up DrJava The following procedure will create a new DrJavaV shortcut on your desktop. Download and run this script. This shortcut will store the DrJava configuration files on the V drive so that they are remembered each time you log in. It also creates the following directories: V:\drjava\lectures V:\drjava\labs V:\drjava\projects It is recommended that the programs written in class be stored in the V:\drjava\lectures directory. When you start DrJava, use the DrJavaV icon. Setting up Chrome and Firefox This is optional, but will allow you to keep bookmarks in Chrome and Firefox that will be restored when you restart VDI. Download and run the setupbrowsers.bat script. This will set up ChromeV and FirefoxV shortcuts that will save your browser configurations on the V drive. The next time your VDI session is started, these shortcuts will result in the saved configuration. Course Overview You can find a course overview here Your First Program: HelloWorld These instructions assume that you are using a development environment called DrJava. Find DrJava on your computer and execute it. Make sure you are using the new icon, the one called Dr. Java, not the one called drjava-stable-xxx - Shortcut. Create a new program called HelloWorld by typing the following in the Definitions pane. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Java is case-sensitive.  You must enter upper and lowercase letters exactly as they appear in the program listing. Save the program by clicking on the Save button. You will be prompted for a location to save your program. Find the V drive and save the program in the drjava\lectures directory. The name should be HelloWorld. Compile the program using the Compile button. If the compiler is successful, the results are saved in a file named HelloWorld.class. Run the program using the Run button. You should see Hello World! in the Console pane (or Interactions pane). This program will be discussed in more detail below.  Here are more detailed instructions for running DrJava.  You can also install DrJava on your own computer. Blackboard can be entered using the following link: http://learn.utsa.edu.  You need to allow popup windows from learn.utsa.edu and utsa.blackboard.com.  If you see a window asking permission to run an application with Publisher dc.blackboard.com and From https://utsa.blackboard.com, click Run. Login to your account. To log on to Blackboard use your myUTSA ID ("abc123" format) and password.  Your myUTSA ID is also used to access ASAP, Air Rowdy wireless network, Student Computing Lab computers, Library computers, and myUTSA email. Become familiar with the different links available and their uses. Note: for this course do not use Blackboard to send email Send an email to the student sitting beside you. Mail -> Create Message -> Browse for Recipients -> Select one or more names and Save -> Type in your subject and message -> Send Algorithms An algorithm is a step-by-step description of how to accomplish a task.  To get an idea for algorithmic thinking, and to learn a little bit about how computers work, consider an algorithm for the following task: Convert a binary number to a decimal number. Naturally, one of the first questions that should be asked is: What is a binary number?  A binary number is a base-2 number, and is composed of just 0s and 1s (called bits).  Almost everything that is digital (such as data on computers, the internet, and DVDs) is represented by binary numbers.  The following table shows the correspondence from zero through nine to binary. Decimal     Binary 0 0 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 9 1001 Each place in a binary number corresponds to a power of two: 1, 2, 4, 8, 16, 32, etc.  For example, going from right to left, the binary number 10110 has: a 0 in the "1" place, a 1 in the "2" place, a 1 in the "4" place, a 0 in the "8" place, and a 1 in the "16" place. Adding up the places where there is a 1 results in 2 + 4 + 16 = 22. Here are more examples: 1111 = 1 + 2 + 4 + 8 = 15 1101 = 1 + 4 + 8 = 13 10101 = 1 + 4 + 16 = 21 101010 = 2 + 8 + 32 = 42 Hopefully, this explanation gives you a good idea of how to convert a binary number to a decimal number.  To become an algorithm, we need to describe how to do the task one step at a time (one bit at time, adding one number at a time, how to start, when to stop, etc.).  Notice there are three things to keep track of: a bit in the binary number, a sum for the decimal number, and a power of two.  Here is one algorithm that does that. Algorithm for converting a binary number to a decimal number Let 1 be the current power of two. Let 0 be the sum. Consider the bits in the binary number going from right to left. Obtain the next bit. If the bit is 1, add the current power of two to the sum; otherwise, do not change the sum. Multiply the current power of two by 2. If there are more more bits to process, go back to Step 4. If there are no more more bits to process, the sum is the decimal number we want as a result. If this algorithm is applied to the binary number 110, this is what is supposed to happen: Running the algorithm on the binary number 110 1.   The current power of two becomes 1. 2. The sum becomes 0. 3. Consider the bits in 110 starting with the 0 on the right. 4. The next bit is 0. 5. The bit is not 1, so the sum does not change (remains at 0). 6. The current power of two becomes 2. 7. There are more bits to process, so go back to step 4. 4. The next bit is 1. 5. The bit is 1, so the current power of two (2) is added to sum, which becomes 2. 6. The current power of two becomes 4. 7. There is another bit to process, so go back to step 4. 4. The next bit is 1. 5. The bit is 1, so the current power of two (4) is added to sum, which becomes 6. 6. The current power of two becomes 8. 7. There are no more bits to process. 8. 6 (the sum) is the result of the algorithm. Activity: Binary Numbers Follow the steps of this algorithm for other binary numbers. Developing any algorithm for a computer has the same issues.  What are the elements of the task and what do they mean?  How can these elements be manipulated one step at a time?  How can a combination of steps be arranged to create an algorithm that solves the task?  Does the algorithm work on a variety of examples?  Can the algorithm be justified by a careful argument? A computer scientist always thinks of other issues that were not considered.  What about negative numbers?  What about fractions?  What if the binary number is written down in a nonstandard way, such as several zeroes at the beginning?  Worrying about where things might go wrong is standard practice in computer science. Activity: Count 1's Develop an algorithm to count the number of 1s in a binary number.  Process the binary number one bit at a time. Activity: More 1's than 0's Develop an algorithm to determine if a binary number has more 1 bits than 0 bits.  Process the binary number one bit at a time. Challenge: Add One Develop an algorithm to add one to (or subtract one from) a binary number. Binary Numbers Writing Simple Programs In computer science, we write programs (instructions for computers) to implement algorithms.  Fortunately, we don't have to write our programs as binary numbers or machine code (ask any old-enough programmer), but we can use a modern programming language like Java.  Also, programmers use development environments to help them write programs.  In these notes, we will assume that you are using a development environment called DrJava. Open your HelloWorld program in DrJava.  If you can't find it, you can always create another one. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Even a simple Java program like HelloWorld consists of several parts that fit together like a jigsaw puzzle. Class Every Java program is implemented by a class.  A class corresponds to a .java file on your computer.  For example, the HelloWorld class should be in the HelloWorld.java file. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Main Method Every Java program contains a class with a main method.  When the program starts, the instructions in the main method are executed. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } Statements Instructions or statements in the body of the main method (statements between { }) are executed one at a time.  Each statement ends in a semicolon (;).  Notice that our main method has only one statement. public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You can add as many System.out.println statements as you want in the main method.  For example, add the following statements inside the main method, and then compile and run your program. System.out.println( ); System.out.println("Take me to your leader!"); Strings A string is a sequence of characters. It is often represented enclosed in quotation marks. System.out.println prints a string and then starts a new line.  If there is no string between the parentheses, it just prints a newline. System.out.print prints a string, but does not start a new line.  For example, the following two statements will print the two strings on one line. System.out.print("I'm sorry Dave."); System.out.print("I'm afraid I can't do that."); If you want to include a " in your string, use the \" escape sequence in the string.  Other escape sequences include \n to include a newline, \t to include a tab, and \\ to include a \. System.out.println("\"I'm sorry Dave.\n I'm afraid I can't do that.\""); System.out.println("\t\t\t\\Hal/"); Activity: Add to HelloWorld Add the statements to your HelloWorld file and run it again. Printing 1 Comments Comments are used to explain the program to other programmers or to yourself.  Any text enclosed between // and the end of the line is completely ignored by the compiler. For example, this comment could be added to the HelloWorld program before the first println statement. // display a greeting in the console pane The compiler also ignores any text between a /* and */  If you have a comment that is longer than one line, then the /*  . . . */ comment is simpler.  For example: /* This is a simple Java program It will print a greeting to the console */ Activity: HelloWorld Comments Add the comments to your HelloWorld file and run again.  Was there any change? Readability In Java, you can add or remove spaces and newlines as long as there is at least one space (or other punctuation) between words.  For example, the HelloWorld class could have been written like: public class HelloWorld{public static void main (String[]args){ System . out . println ("Hello World!");}} However, you should follow the conventions given and illustrated in the book.  Making your program unreadable (obfuscation) will result in points taken off.  Here are a few guidelines. Put each class header, method header, and statement on a line by itself. Use indentation to indicate program structure.  Increase the indentation after a {.  Decrease the indentation after a }.  Use a consistent number of spaces for indentation.  With DrJava, you can get a reasonable indentation using the following sequence of menu commands. Edit -> Select All Edit -> Indent Line(s) The names of classes should be capitalized.  The names of methods should start with a lower-case letter.  If a name consists of more than one word, then omit the spaces and capitalize each following word, for example, MoreThanOneWord or moreThanOneWord. Use blank lines to separate methods in a class. Errors Much of your programming time will be occupied by debugging, finding and fixing bugs, which are errors in your program. A syntax error indicates an ill-formed program.  Part of the job of the compiler is to detect and list all of your syntax errors.  Compilers are good at finding syntax errors, but usually provide lousy error messages.  A lot of the time you will need to figure out what is wrong at (or around) the location of the error given by the compiler.  Common syntax errors include misspelled words, improper capitalization, missing semicolons, incorrect punctuation, and mismatched parentheses or braces. A program has a logic error if it doesn't perform the task correctly when it is executed.  For example, this statement in the HelloWorld program would be incorrect because it doesn't print the right message. System.out.println("Hollow wood?"); A runtime error is a logic error that Java detects while your program is running.  When this happens, your program will crash.  Examples of runtime errors include division by zero and trying to access the 10th character of a string that only has 5 characters. Activity: SpellingChequer Write a program named SpellingChequer to print the following: Eye halve a spelling chequer It came with my pea sea It plainly marques four my revue Miss steaks eye kin knot sea. Activity: Print Diamond Write a program named Diamond to print the following: ** **** ****** ****** **** ** Activity: QuotesAndSlashes Write a program named QuotesAndSlashes to print the following: /\ /""\ /""""\ \""""/ \""/ \/ Program Progress 2 Your First Lab The labs will be due by Tuesday of most weeks.  (Always check your calendar.)  Generally, that means you start programming and ask questions during one week, and finish the program and upload to Blackboard at the beginning of the next week.  You may collaborate on the labs, but copying is cheating. Read the lab assignment Create a folder named lab0 in V:\drjava\labs. The full path of this directory is V:\dijava\labs\lab0. Start the lab assignment in DrJava: public class Initials { public static void main(String[ ] args) { System.out.println("Lab 0 written by YOURNAME"); } } Save this in the V:\drjava\labs\lab0 directory. The complete path to the saved file will be V:\drjava\labs\lab0\Initials.java Compile and run the program. Implement the program so that it correctly completes the task in every detail. Save the output of the program into a file named InitialsOutput.txt in your lab0 folder.  [In DrJava, you can right-click on the Interactions pane and select Save Copy of Interactions.] Zip your lab0 folder.  Right click on lab0 and select Send To -> Compressed (zipped) Folder (or 7-Zip -> Add to "lab0.zip"). Submit the lab to Blackboard. Assignments -> Lab 0 (bold link) -> Attach File (find file and click OK) -> Submit If successful, you will see Lab 0 listed on your Submitted tab (Assignments -> Submitted).  If you were unsuccessful, read this. Using Static Methods Consider writing a program to print out the lyrics of "Old MacDonald Had a Farm" (a variation of these lyrics).  We could write a class that prints each line in a main method. public class OldMacDonald { public static void main(String[] args) { // print title System.out.println("Old MacDonald Had a Farm"); System.out.println( ); // print first verse System.out.println("Old Macdonald had a farm, E-I-E-I-O"); System.out.println("And on his farm he had a cow, E-I-E-I-O"); System.out.println("With a moo-moo here and a moo-moo there"); System.out.println("Here a moo there a moo"); System.out.println("Everywhere a moo-moo"); System.out.println("Old Macdonald had a farm, E-I-E-I-O"); System.out.println( ); // print second and third verses (not done yet) } } However, there is some redundancy, and the program does not reflect the structure of the song, which makes the program more difficult to understand and maintain.  We can apply procedural decomposition to identify common subtasks and to separate the overall task into several subtasks.  Then, each subtask can be implemented with a static method. Common Subtask An example of a common subtask is the "Old Macdonald had a farm, E-I-E-I-O" line, which appears several times in the song.  We can write a static method that just prints this one line.  This method is named oldMacLine. // This method prints the Old Macdonald line public static void oldMacLine( ) { System.out.println("Old Macdonald had a farm, E-I-E-I-O"); } Then, we can rewrite the main method to call the oldMacLine method to print this line as needed.  Note that the new method is included in the class. public class OldMacDonald { public static void main(String[] args) { // print title System.out.println("Old MacDonald Had a Farm"); System.out.println( ); // print first verse with method calls oldMacLine( ); System.out.println("And on his farm he had a cow, E-I-E-I-O"); System.out.println("With a moo-moo here and a moo-moo there"); System.out.println("Here a moo there a moo"); System.out.println("Everywhere a moo-moo"); oldMacLine( ); System.out.println( ); // print second and third verses (not done yet) } // This method prints the Old Macdonald line public static void oldMacLine( ) { System.out.println("Old Macdonald had a farm, E-I-E-I-O"); } } Separating a Task into Subtasks An example of separating the overall task into subtasks is separating the song into the title and its verses.  That is, we might have the following algorithm in mind. Print the title. Print the first verse. Print the second verse. Print the third verse. We could write a separate method for the title and each verse.  Here is a method for the first verse, appropriately named firstVerse. // This method prints the first verse of Old MacDonald public static void firstVerse( ) { oldMacLine( ); System.out.println("And on his farm he had a cow, E-I-E-I-O"); System.out.println("With a moo-moo here and a moo-moo there"); System.out.println("Here a moo there a moo"); System.out.println("Everywhere a moo-moo"); oldMacLine( ); System.out.println( ); } We can rewrite the main method to call the firstVerse method.  Note again that the new method is included in the class.  Programming by adding one method at a time and rewriting to call the new method is known as iterative enhancement or stepwise refinement. public class OldMacDonald { public static void main(String[] args) { // print title System.out.println("Old MacDonald Had a Farm"); System.out.println( ); // print first verse with a method call firstVerse( ); // print second and third verses (not done yet) } // This method prints the Old Macdonald line public static void oldMacLine( ) { System.out.println("Old Macdonald had a farm, E-I-E-I-O"); } // This method prints the first verse of Old MacDonald public static void firstVerse( ) { oldMacLine( ); System.out.println("And on his farm he had a cow, E-I-E-I-O"); System.out.println("With a moo-moo here and a moo-moo there"); System.out.println("Here a moo there a moo"); System.out.println("Everywhere a moo-moo"); oldMacLine( ); System.out.println( ); } } The order that the three methods are listed in the class do not matter.  The flow of control will proceed by first executing the statements in the main method.  When a statement calls another method (a method call), the statements in that method will be executed from start to finish, and then control will return to the method call. Activity: OldMacDonald Revision 1: Revise the OldMacDonald program so that the main method also calls a method named title to print the title. Old MacDonald 1 Activity: OldMacDonald Revision 2: Revise the OldMacDonald program so that the main method, in addition to calling title, also calls secondVerse and thirdVerse.  Also, identify another common subtask and write a method for it. Summary of Syntax The syntax for a class is: public class ClassName {     method(s) } A class with name ClassName should be saved in ClassName.java. The syntax for the main method is: public static void main(String[ ] args) {     statement(s) } The syntax for other static methods is: public static void methodName( ) {     statement(s) } The syntax for various print statements is: System.out.println(string); System.out.print(string); System.out.println( ); The first println statement prints the string followed by a newline.  The print statement prints the string without any newline.  The last println statement just prints a newline.  A string is a sequence of characters between quotation marks ("). The syntax for a method call statement is: methodName( ); A method call executes the statements in the method and returns control to the next statement (if any) after the method call.  next notes  next notes