JAVA SSD

  • 格式:doc
  • 大小:2.41 MB
  • 文档页数:69

Unit 1. Class Design∙1.1 Java Applications ∙ 1.2 Designing Classes ∙ Exam 11.1 Java Applications∙ 1.1.1 Applications in Java ∙ 1.1.2 Using Eclipse∙ 1.1.3 Beginning with the Java API ∙ 1.1.4 Console I/O∙ 1.1.5 Exception Objects ∙ 1.1.6 Code Conventions ∙ 1.1.7 Javadoc ∙ Practical Quiz 1 ∙ 1.1.8 Debugging∙ 1.1.9 Debugging with Eclipse ∙ Practical Quiz 2∙ Multiple-Choice Quiz 1 ∙Exercise 11.1.1 Applications in Java∙ Applets in Java ∙Applications in JavaApplets in JavaJava programs come in many flavors: applets, servlets, and applications. Applets are referenced from web pages and interpreted by web browsers. Every applet contains a public class that extends the class Applet .The following is an applet that outputs a message: 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: import java .applet .*; import java .awt .*;public class MyApplet extends Applet {public void paint (Graphics g ) {g .drawString ("This is an applet!\n", 10, 10); } }Listing 1 MyApplet.javaApplications in JavaJava applications are "stand-alone" programs, interpreted by a Java interpreter (not a web browser) on a host system. To execute a Java application, the user types a command that invokes the Java interpreter on the specified application.Figure 1 Command to execute MyApplicationThe command java calls the Java interpreter and MyApplication is the name of the class that will be executed. The operating system begins execution by calling the method main in the class MyApplication. Applications can consist of one or many classes; one of those classes must have a method main. The method main has the following signature.public static void main(String[] args)The method main has one input parameter, a String array that holds any command-line arguments that the user may have specified when typing the java command. Command-line arguments allow the user to pass information to the application. We will not use command-line arguments in this course.The following is a simple application that displays the words "This is my first application!" on the screen.class MyApplication {public static void main(String[] args) {.out.println("This is my first application!");Listing 2 MyApplication.javaThe class containing method main must be public. The class declaration may or may not have an extends-clause; in this respect, applications differ from applets. Class names should have the first character of each word capitalized and they should not contain any underscores ( _ ). For example, the name WordCount adheres to the convention, whereas wordCount, wordcount, and word_count do not. The file containing the source code must have the same name as the class it contains and use the .java extension. For example, the file containing the class WordCount must be named WordCount.java.The following figure shows the output of class MyApplication.Figure 2 Execution of MyApplication© Copyright 1999-2006, iCarnegie, Inc. All rights reserved.1.1.2 Using Eclipse∙Introduction∙Create the Project∙Create the Class∙Compile the Class∙Execute the ApplicationIntroductionAn Integrated Development Environment (IDE) is a tool used by system developers to assist them in the various phases of system development. Eclipse is an open source IDE that supports several programming languages. Eclipse comes with a Java Development Environment (JDE)that includes a syntax-highlighting editor, compiler, debugger, class navigator, and file/project manager. The functionality of Eclipse can be extended with plug-ins such as UML plug-ins for Object-Oriented modeling. In this page, we will show how to create and execute the application MyApplication.Create the ProjectThe first step is to create a Java project:1.On the File menu, point to New, and then click Project.2.In the New Project wizard, click Java in the left pane, click Java Project in the right pane, and then clickNext.Figure 1 New Project wizard3.In the Project name box, type MyApplication. Click the Use default check box and then click Finish.Figure 2 New Java Project dialog box4.Eclipse will create a new Java project and display the Java perspective, one of the Eclipse interfaces forworking on a Java project. The Java perspective offers a number of tools including a code editor, file browser, and class browser.Figure 3 Java perspective5.You can change the perspective of the project. On the Window menu, point to Open Perspective andclick the desired perspective. You can also click the desired perspective's icon on the shortcut bar at the far left of the window.Figure 4 Perspectives shortcut barCreate the Class1.On the File menu, point to New and then click Class.2.In the New Java Class wizard, type MyApplication in the Name box and then click Finish.Figure 5 New Class wizard3.Eclipse will display a template for a new class named MyApplication.Figure 6 Template for a new class4.On the Window menu, point to Open Perspective and then click Java Browsing. This perspectivecontains a Java editor and several views of the project. If the user clicks an element in the Types orMembers view, the editor will display the code for that element.o The Projects view shows Java projects, source folders, external and internal libraries.o The Packages view lists the packages of classes in the selected project.o The Types view lists the classes in the selected package.o The Members view shows the variables and methods in the selected class.5.Enter the code for MyApplication. Refer to Listing 2 on 1.1.1 Applications in Java.Figure 7 Code of MyApplication.javaCompile the ClassEclipse includes an incremental Java compiler. When you enter a line of code that contains an error, the editor will display, on the right, a red mark next to that line of code.1.Introduce a syntax error by deleting the semicolon ( ; ) at the end of the line that containsSystem.out.println. The editor will display a red mark.2.Point to the red mark to display the error message.Figure 8 Syntax error message3.Correct the error by adding the semicolon ( ; ). The red mark will disappear.Execute the Application1.Begin by creating a launch configuration for the MyApplication project. Click MyApplication inthe Projects view, click the arrow to the right of the Run button on the toolbar, and then click Run.Figure 9 Run the Java application2.In the Run dialog box, type MyApplication in the Main class box and then click Run.Figure 10 Creating configuration3.Once the launch configuration is set up, the user can execute the application by clicking the arrow to theright of the Run button on the toolbar, pointing to Run As and then clicking Java Application.Figure 11 Running the application4.If the Java class has not been saved, Eclipse will display a dialog box for saving the files of the Javaproject. Click OK.Figure 12 Save the Java project5.Eclipse will display the message in the Console view that appears at the bottom of the window.Figure 13 Console output6.The Console view displays the output of the application. If an application usesprompts to solicit input from the user, the prompts are displayed in the Console view. The user responds to a prompt by typing in the Console view. The Console view color codes standard output, standard error, and standard input. (For a discussion of the java.io package, see page 1.1.4 Console I/O). The default colors are:o Blue for standard outputo Red for standard error (error messages and prompts)o Green for standard input© Copyright 1999-2006, iCarnegie, Inc. All rights reserved.1.1.3 Beginning with the Java API∙Introduction∙Packages and the import Statement∙The ng.String Class∙The java.util.StringTokenizer Class∙The Wrapper ClassesIntroductionThe Java Application Programming Interface (API)represents an extensive Java library. These libraries are carefully written, robust and extensively tested.The documentation for the Java API is generated by the Javadoc tool. Javadoc produces a set of HTML pages from the Javadoc comments in a Java source file. Javadoc comments document an application's classes, variables, and methods. We will use Javadoc comments in our source code so the documentation for our applications will have the same organization and format as that of the Java API.Packages and the import StatementThe classes in the Java API are grouped into packages. A package is simply a collection of related classes. The following is an example of a package name:java.utilThe fully qualified name of a class that is part of a package is the package name and the class name separated by a dot.java.util.GregorianCalendarTo declare two variables of type GregorianCalendar, we would type:java.util.GregorianCalendar firstDate =new java.util.GregorianCalendar(2004, 1, 1);java.util.GregorianCalendar lastDate =new java.util.GregorianCalendar(2004, 12, 31);Typing the fully qualified name of a class is tedious and the resulting code is difficult to read. For this reason, Java offers the import statement. It is used to "import" a class—or an entire package of classes—into a file. An imported class can be referenced using its simple name, the fully qualified name minus the package name. An import statement consists of the keyword import, a fully qualified name, and a semicolon:import java.util.GregorianCalendar;This statement, placed at the top of a file, makes it possible to write: GregorianCalendar firstDate = new GregorianCalendar(2004, 1, 1); GregorianCalendar lastDate = new GregorianCalendar(2004, 12, 31);This is far more convenient, as the package name needs to be mentioned only once in the import statement. Often, programmers use several classes from the same package. Rather than using an import statement for each class, the entire package is imported: import java.util.*;The asterisk ( * ) acts as a wildcard, representing all the classes in the specified package.The asterisk is convenient. For example, consider an application that uses the asterisk to import all the classes in the package java.io but uses only one. New code that uses other classes in java.io can be added without adding more import statements. Many programmers use the asterisk, even when they need just one class in a package, because it is quick to type and it does not incur any overhead: importing a package does not slow compilation or execution, nor does it increase the size of the byte code.Finally, it is not necessary to import ng. The ng package is implicitly imported into all Java applications. All applications can reference classes in the ng package using their simple names.For each of the classes discussed below, a link to its API documentation is provided. We encourage you to follow these links and become familiar with the many useful methods in these classes.The ng.String ClassSince Java provides no primitive string type, the ng.String class is heavily used. Java does include the string literal, a sequence of characters within double quotes such as "abc". A string literal is an instance of class String.The following is a list of some of the methods defined in class String: ∙String(). Constructs a new String object that represents an empty character sequence.∙String(char[] value). Constructs a new String object that represents the sequence of characters contained in the character array.∙String(String original). Constructs a new String object that represents the same sequence of characters as the argument.∙int length(). Obtains the number of characters in the String.∙char charAt(int index). Returns the character at the specified index.∙boolean equals(Object anObject). Returns true if the specified Object represents a String with the same sequence of characters.∙int indexOf(int ch). Returns the index of the first occurrence of the character.∙int indexOf(String str). Returns the index of the first occurrence of the String.∙boolean startsWith(String prefix). Checks if the String has the specified prefix.∙String substring(int beginIndex, int endIndex). Returns a substring.Java also provides the String concatenation operator ( + ). It is a binary operator that requires two String operands. It concatenates these operands, returning the result in a new String. The following two lines represent equivalent String objects: "one" + "two""onetwo"Notice that no separator is placed between the operands in the result.Every class in the Java API has a method called toString. This method returns the String representation of an object. This means every instance of a Java API class has a String equivalent:"hello " + anyObject.toString()As a convenience, if one of the operands to the concatenation operator is an object (other than a String, of course), that object's toString method will be automatically invoked, thus enabling concatenation to take place. This means we can write: "hello " + anyObjectIf a primitive is the operand to the String concatenation operator, it will be replaced by an equivalent object and that object's toString method will be called. This means we can write:"hello " + 5Without automatic translation, we would have to write:"hello " + (new Integer(5)).toString()Since the plus symbol ( + ) is also used for addition, at least one of its operands must be a String for it to work as the concatenation operator. Observe the following: stdOut.println(2 + 3 + "5"); // prints 55, not 235stdOut.println(2 + "" + 3 + "5"); // prints 235The following example illustrates the use the methods in the String class: ∙Download StringClassDemo.javaThe java.util.StringTokenizer ClassTokenizing is the process of breaking a string into smaller pieces called tokens. Tokens are separated, or delimited, by a character or group of characters. For example, if the following string is tokenized using white space as the delimiter, the result will be five tokens."This string has five tokens"White space is the most common delimiter (white space includes the space character, the tab character, the newline character, the carriage-return character, and the form-feed character); other popular delimiters include the underscore ( _ ) and the comma ( , )."This_string_has_five_tokens""This,string,has,five,tokens"Any character, though, can act as a delimiter. For example, if the string "This string has five tokens" is tokenized using the character "i" as the delimiter, the result will be four tokens:∙"Th"∙"s str"∙"ng has f"∙"ve tokens"Delimiters such as "i", though, are uncommon.The StringTokenizer class is part of the package java.util. The following is a list of some of the methods in the class StringTokenizer:∙StringTokenizer(String str). Constructs a string tokenizer. The tokenizer uses the default delimiter set, white space.∙StringTokenizer(String str, String delim). Constructs a string tokenizer. The argument delim contains the character delimiters for separating tokens.∙boolean hasMoreTokens(). Tests if there are more tokens to extract.∙String nextToken(String delim). Returns the next token in the string.∙int countTokens(). Obtains the number of tokens left to be extracted, not the number of tokens in the string.The following application stores the inventory data for a product (name, quantity, and price) in a String. The String is delimited by the underscore character ( _ ). The application uses a StringTokenizer object to extract the tokens from the String.1: 2: 3: 4: 5: 6: 7: 8: 9: 10:import java.util.*;public class ProductInfo {public static void main(String[] args) {String data ="Mini Discs 74 Minute (10-Pack)_5_9.00"; StringTokenizer tknzr =new StringTokenizer(data,"_");= tknzr .nextToken ();= tknzr .nextToken ();= tknzr .nextToken ();.out .println ("Name: " + name );.out .println ("Quantity: " + quantity );.out .println ("Price: " + price );Listing 1 ProductInfo.javaWhen the application is executed, the inventory data is displayed.Figure 1 Execution of ProductInfoThe following example illustrates the use of the StringTokenizer class. ∙ Download StringTokenizerClassDemo.javaThe Wrapper ClassesThere are many classes in the Java API, and programmers define many more still. Yet, only a few primitives are available. In some respects, it would be nice if all data in Java programs were treated in the same, consistent manner. To make this a reality, Java offers classes that mimic the primitives. There is one such class for each primitive. Together, these classes are called the wrapper classes :∙ ng.Byte∙ ng.Short∙ ng.Integer∙ ng.Long∙ng.Character∙ ng.Float∙ ng.Double∙ ng.BooleanNotice that names of the wrapper classes are very similar to their primitivecounterparts. A wrapper class contains a single field whose type is the corresponding primitive. For example, the class Integer contains one field of type int. The following application illustrates the use of the Integer wrapper class. class WrapperConversion {public static void main (String [] args ) {= new Integer (100);7: 8: 9: 10: 11: 12: 13:14: 15: 16: 17: 18: int intValue = objectValue .intValue ();long longValue = objectValue .longValue ();double doubleValue = objectValue .doubleValue ();String stringValue = objectValue .toString ();System .out .println ("objectValue: " + objectValue );System .out .println ("intValue: " + intValue );System .out .println ("longValue: " + longValue );System .out .println ("doubleValue: " + doubleValue );System .out .println ("stringValue: " + stringValue );}}Listing 2 WrapperConversion.javaThe wrapper classes are a part of the package ng, and therefore do not need to be explicitly imported. The application creates a wrapper object to store an integer, and then it finds the equivalent long, double and String value. The following figure shows the result of the execution of WrapperConversion:Figure 2 Execution of WrapperConversionIn addition, the wrapper classes provide methods for converting primitives to String objects and String objects to primitives. For example, Integer.toString(10) converts the integer value 10 to the String "10", and Integer.parseInt("10") converts the String "10" to the integer value 10.We can enhance the application ProductInfo. The method nextToken returns a String, which isn't very useful when the token being extracted is a numeric value like quantity or price. We can use the class Integer to convert the String containing the quantity to an integer value; we can use the class Double to convert the String containing the price to a double value. Now it is possible to compute the total value of the product.java .util .*;class ProductValue {public static void main (String [] args ) {= "Mini Discs 74 Minute (10-Pack)_5_9.00";= new StringTokenizer (data , "_");11: 12:13: 14: 15: 16: 17: 18: 19: 20: String name = tokenizer .nextToken (); int quantity = Integer .parseInt (tokenizer .nextToken ());double price = Double .parseDouble (tokenizer .nextToken ());System .out .println ("Name: " + name );System .out .println ("Quantity: " + quantity );System .out .println ("Price: " + price );System .out .println ("Total: "+ quantity * price );}}Listing 3 ProductValue.javaThe following figure shows the result of the execution of ProductValue:Figure 3 Execution of ProductValue© Copyright 1999-2006, iCarnegie, Inc. All rights reserved.1.1.4 Console I/O∙The java.io Package ∙ Reading Primitive ValuesThe java.io PackageThe package java.io is loaded with classes. This discussion will focus primarily on only two of them. The class java.io.BufferedReader is used for input. The class java.io.PrintWriter is used for output.The following is a template for classes that use console I/O:1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: import java .io .*; // contains BufferedReader and PrintWriterpublic class AnyClassUsingIO {private static BufferedReader stdIn =new BufferedReader (new InputStreamReader (System .in ));private static PrintWriter stdOut =new PrintWriter (System .out , true );private static PrintWriter stdErr =new PrintWriter (System .err , true );/* other variables *//* methods */Listing 1 Template of a class using IOThe private modifier will be discussed later. In short, it prevents other classes from using the variables stdIn, stdOut, and stdErr.∙ System.in is the "standard" input stream. Typically, this stream corresponds to keyboard input. ∙ System.out is the "standard" output stream. Typically, this stream corresponds to screen output. ∙ System.err is the "error" output stream. Typically, this stream corresponds to screen output.System.out is used to display typical and regular program output. System.err is used to display prompts and error messages. This is just a convention that makes it easy for programmers and users to identify the different types of output.System.out and System.err could be used for output directly. It is more convenient, however, to wrap each in a PrintWriter object. The class PrintWriter has two printing methods: println and print. The former automatically follows the output with a new line; the latter does not. The methods println and print can take many types of arguments. Consider the following example using println: 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: import java .io .*;public class PrintlnDemo {private static BufferedReader stdIn =new BufferedReader (new InputStreamReader (System .in ));private static PrintWriter stdOut =new PrintWriter (System .out , true );private static PrintWriter stdErr =new PrintWriter (System .err , true );public static void main (String [] args ) {stdOut .println ("A line of output.");stdOut .println (5);stdOut .println (7.27);stdOut .println (true );stdOut .println ();}}Listing 2 PrintlnDemo.javaFollowing is the output of PrintlnDemo:Figure 1 Execution of PrintlnDemoCompare the output of PrintlnDemo with the output of PrintDemo, a class that uses print: 1: 2: 3:4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: import java .io .*;public class PrintDemo {private static BufferedReader stdIn =new BufferedReader (new InputStreamReader (System .in ));private static PrintWriter stdOut =new PrintWriter (System .out , true );private static PrintWriter stdErr =new PrintWriter (System .err , true );public static void main (String [] args ) {stdOut .print ("A line of output.");stdOut .print (5);stdOut .print (7.27);stdOut .print (true );stdOut .println ();}}Listing 3 PrintDemo.javaFollowing is the output of PrintDemo:Figure 2 Execution of PrintDemoThe String concatenation operator is often used to construct arguments for println and print:stdOut.println("The number five: " + 5);The second argument to the PrintWriter constructor is a Boolean that indicates whether automatic flushing should occur. When programs produce screen output, it does not go directly to the screen. It goes to a holding area called a buffer . When the buffer is full, it is automatically flushed. Flushing empties the buffer and sends its contents to the screen. However, most output statements do not fill the buffer so output sits in the buffer instead of being displayed on the screen. Since programmers expect output to be displayed immediately, the class PrintWriter has an optional, automatic flushing feature called auto-flush . When the second argument to the PrintWriter constructor is true, auto-flush is enabled and the buffer isautomatically flushed after every call to method println —but not after calls to method print. The programmer can use the method flush to flush the buffer after a call to method print. The following example illustrates the use of method flush: 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: import java .io .*;public class Hello {private static BufferedReader stdIn =new BufferedReader (new InputStreamReader (System .in ));private static PrintWriter stdOut =new PrintWriter (System .out , true );private static PrintWriter stdErr =new PrintWriter (System .err , true );public static void main (String [] args ) throws IOException {stdErr .print ("Please enter you name on this line: ");stdErr .flush ();String input = stdIn .readLine ();stdOut .println ("Hello " + input );}}Listing 4 Hello.javaThe exception IOException will be discussed in page 1.1.5 Exception Objects . Notice that stdErr, the standard error output stream, is used to output prompts. If the call to method print that outputs the prompt is not followed by a call to method flush, the user will probably not see the prompt right away. This is usually undesirable. System.in could be used for input directly. Its capabilities, however, are primitive as it can only read one character at a time. Reading a line of input this way would be cumbersome. Wrapping System.in in a BufferedReader object makes it possible toread entire lines of input. The BufferedReader method to read an entire line is readLine.A call to method readLine will cause the program to wait, or block, until the user types a line of information. When the user presses the ENTER key, the line is read by method readLine and returned as a String.Following is the output of Hello:Figure 3 Execution of HelloReading Primitive ValuesNot all input is intended to be used as a String. For example, a program may be prompting for an integer. An integer can be extracted from the input using a method in the wrapper class for integers. The following line of code shows how this is done: int value = Integer.parseInt(stdIn.readLine());Using the static method parseInt from the class Integer, the input, read as a String, is converted to an int so it may be stored in an int variable. Most wrapper classes have a similar parse method: the class Double has the method parseDouble while the class Float has the method parseFloat. The exception is the class Boolean class; it uses method getBoolean. To extract a character from the input, use the method charAt to retrieve the character in the String returned by method readLine. Or, use the method read instead of method readLine. However, using method read will require a cast before the assignment can be made since method read returns an int, not a char.The following class uses a StringTokenizer object to read three integers from one line of input:1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15:import java.io.*;import java.util.*;public class ReadThreeIntegers {private static BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));private static PrintWriter stdOut =new PrintWriter(System.out, true);private static PrintWriter stdErr =new PrintWriter(System.err, true);public static void main(String[] args)throws IOException {。