Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 20 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
20
Dung lượng
458,7 KB
Nội dung
your procedure are. Comments also help when you go back and add new func- tionality to your code because you will be less likely to be confused by what you had previously done. There are two basic types of comments in Java—single-line comments and multi-line comments. If you just want to make a note about a par- ticular line of code, you usually precede that line of code with a single-line com- ment as shown here: //The following line of code prints a message using standard output System.out.println("Hello, World!"); Single-line comments start with double slashes //. This tells the compiler to dis- regard the following line of code. After the double slashes, you can type anything you want to on that single line and the compiler will ignore it. Single line comments are also commonly used to temporarily disable a line of code during the debugging process. Simply add the double slashes at the begin- ning of the line of code to make the compiler skip the line. You typically do this if you want to test a modified version of the commented line or if you need to see how the program runs without executing that particular statement. This way, you don’t have to delete it and you can replace the statement simply by removing the double slashes. Sometimes you might want to write a comment that spans more than one line of code. You can precede each line with double slashes if you choose to, but Java allows you to accomplish this more easily. Simply start your comment with a slash followed by an asterisk: /*. You can type anything you want to after this, including carriage returns. To end this comment, all you need to do is type */. /* I just started a comment I can type whatever I want to now and the compiler will ignore it. So let It be written So let It be done I'm sent here by the chosen one so let It be written so let It be done to kill the first born pharaoh son I'm creeping death from Metallica's song, Creeping Death I guess I'll end this comment now */ Everything in between the start and end of this comment is considered free text. This means you can type anything you want to within them. If you take another look at the HelloWorld source code, you will notice that I used a multi-line com- ment. I typed the name of the HelloWorld program and then followed with sev- eral more lines. I preceded every line with an asterisk. You don’t have to do this. I only did it to make the comments stand out more. Feel free to develop your own style of commenting your code, but keep in mind that you or someone else TRICK 18 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 18 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. might need to refer to the source code, so try to make your comments easy to understand. There is actually another form of multi-line commenting used in Java. It has the added capability to be converted into HTML documentation using the javadoc utility included with the JDK. The main() Method When running a Java application, the main() method is the first thing the inter- preter looks to. It acts as a starting point for your program and continues to drive it until it completes. Every Java application requires a main() method or it will not run. In this section, I point out what you should understand about it because you’ll be using it often. In fact, you use it in every application you write. The main() method always looks just like it did when you programmed the HelloWorld application. public static void main(string args[]) { Let’s take a closer look at the parts of the main() method: • The public and static keywords are used in object-oriented program- ming. Simplified, public makes this method accessible from other classes and static ensures that there is only one reference to this method used by every instance of this program (class). Static methods are also referred to as class methods, because they refer to the class and not specific instances of the class. This is a difficult concept to understand at this point. You can simply gloss over it for now. • The void keyword means that this method does not return any value when it is completed. • main is the name of the method, it accepts a parameter—String args[]. Specifically, it is an array (list) of command-line arguments. As is the case with all methods, the parameters must always appear within the paren- theses that follow the method name. • Within the curly braces of the main() method, you list all the operations you want your application to perform. I stated earlier that every Java appli- cation requires a main() method; however, it is possible to write a Java source code file without defining a main() method. It will not be consid- ered an application, though, and it won’t run if you use the java com- mand on it. Now your head might be spinning at this point. Don’t let all this make you forget what I stated earlier. The main() method is simply the driver for your application. HINT 19 C h a p t e r 1 G e t t i n g S t a r t e d JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 19 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing Your First Applet Applets differ from stand-alone applications in that they must be run within a Java-enabled browser and they don’t require a main() method. In this section, you write an applet, learn how to incorporate it into an HTML document, run it within your browser and also by using the appletviewer utility, which is built into the JDK. The appletviewer utility allows you to run applets from the com- mand prompt, outside of your browser. Applets are covered in greater detail in Chapter 8, “Writing Applets.” At this point, your goals are to understand what an applet is, to learn how to create a simple one, and to understand how an applet differs from an application. Back to the HelloWeb Applet! Remember the project introduced at the beginning of this chapter? In this sec- tion, you actually learn to create the HelloWeb applet. This applet performs a task similar to that of the HelloWorld application, but it runs within a Web browser instead of as a stand-alone application. Applets add a great deal of life to Web doc- uments. If you include an applet in a Web document and publish it on the Inter- net, anyone can browse to it and run your program without having to explicitly download it. In the real world, you can play Java games online. The source code, although only one statement longer than the HelloWorld application, is a bit more complex. Now, you will create this applet. /* * HelloWeb * A very basic Applet */ import java.awt.Graphics; public class HelloWeb extends java.applet.Applet { public void paint(Graphics g) { g.drawString("Hello, World Wide Web!", 10, 50); } } Copy or type this source code into your text editor and name the file Hello- Web.java. Even though this is an applet, you compile it exactly the same way as you do applications. Just use the javac command. After it’s compiled, your applet is still not ready to run. Figure 1.7 shows what will happen if you try to run this as an application, further emphasizing the fact that all applications must define a main() method. 20 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 20 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Writing the HTML In order to run the applet, you need to write an HTML document and include the applet within it. You don’t need to know much about HTML for the purposes of this book. You write only the bare essentials in the HTML document and include the applet. This is the listing for the HTML document: <html> <head> <title>HelloWeb Applet</title> </head> <body> <h1 align=center>HelloWeb Applet</h1> <center> <applet name="HelloWeb" code="HelloWeb.class" width=250 height=100></applet> </center> </body> </html> Copy or type this HTML code into your text editor and save it as helloweb.html in the same directory as your applet. The name is not all that important but the .html extension is. Running the Applet After you have created the HTML file, you are ready to run your applet. You can do this in one of two ways. First, you can use the appletviewer tool by typing the following at the command prompt: appletviewer helloweb.html Figure 1.8 shows what the appletviewer window looks like while running the HelloWeb applet. 21 C h a p t e r 1 G e t t i n g S t a r t e d FIGURE 1.7 There is no main() method, so it cannot be run as an application. JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 21 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 22 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r Next you can double-click your helloweb.html icon to run the applet in your browser. Congratulations! You’ve just written and run your first Java applet. If your applet is running fine using appletviewer, but you can’t get it to run inside your browser, you should make sure that you have the latest Java plug-in. I will quickly explain the new syntax that appears in this applet’s source code. First, there is the import statement: import java.awt.Graphics; This code imports the Graphics class. By importing classes, you tell the JRE where to look for the class definition so you can use it in your code. Your applet uses the Graphics class, so you must import it. Your applet also uses the extends keyword: public class HelloWeb extends java.applet.Applet { You can see that it is part of your class definition statement. This is what actually makes your program an applet. Extending a class, such as the Applet class, is a way of reusing the functionality of another class that has already been defined and gives you the capability to extend its characteristics and capabilities. When one class extends another, it is referred to as a subclass and the class it extends is called its super class. This is one of the benefits of object-oriented programming. One last thing to understand is the way you instructed your applet to print a message. Public void paint(Graphics g) { g.drawString("Hello, World, Wide, Web!", 10, 50); } FIGURE 1.8 Using the appletviewer to view your applet. JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 22 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The pre-existing Applet class already defines a paint() method. Here you over- ride it to do what you want it to do. You tell the Graphics class to draw the string "Hello, World Wide Web!" inside of your applet with g.drawString(). The num- bers that follow your string in your parameter list are the x, y coordinates describing where to paint the string. You’ll learn more about this in Chapter 8. Summary You accomplished a lot in this chapter. You learned that Java is a platform- independent, object-oriented programming language that you can use to write applications and applets. You installed the Software Development Kit and set it up, giving your system the capability to compile and run Java programs. You wrote your first application, learned how to use the javac command to compile it and the java command to run it. After you successfully ran the HelloWorld application, you looked back and examined your code. You learned the basics of Java syntax. You also wrote your first applet and learned the basic differences between applications and applets. You learned how to include an applet within an HTML document. Finally, you learned how to run an applet by using the appletviewer utility and also how to run it in your browser. You are ready to take 23 C h a p t e r 1 G e t t i n g S t a r t e d INTHEREAL WORLD In the real world, applications and applets typically do much more than simply print a message to the screen. Programmers to tend to use the System.out.println() method while debugging code. Although you didn’t use this in your first applet, it is possible to use standard output in applets. Java- enabled Web browsers typically have a Java console, or window that displays these types of messages. For example, if you’re using Internet Explorer, you can call up the Java console by selecting that option from the View menu. Standard output is useful when debugging your code. If you are having difficulty getting your program to run the way you intend it to run, you can print infor- mation about the program as it is running. This way, you can see the state of the program at key locations in the code. This will, more often than not, lead to the source of the problem when you see that some specific part of the program does not look the way it should look while it is running. At this point, you will have to trace only the code that affects that part of the program. JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 23 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. on some new challenges. In the next chapter you learn about variables, data types, mathematical operations, and how to accept simple user input. 24 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r CHALLENGES 1. Write a Java application that prints your first name to standard output. 2. Rewrite your Java application from challenge #1 to print your last name to standard output without deleting any lines by commenting out the line you don’t need and adding the one that you do. 3. Write a Java application that prints two separate lines to standard output by repeating the System.out.println() statement using a different sentence. 4. Write an applet that displays your name and run it with both the appletviewer utility and with your browser. JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 24 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. I n this chapter, you learn how to use variables, data types, and standard input/output to create an interactive appli- cation. You start by learning what variables are and what they are used for. Then you learn what the primitive data types are and how they are assigned to variables. After you understand variables, you learn how to work with numbers and use mathe- matical operations. After that you learn about strings and how to accept simple user input. Finally, you put all this knowledge together and build an application that uses standard output, accepts user input, and works with strings and numbers. In this chapter, you will • Learn to use data types • Declare and name variables • Work with numbers • Get simple user input • Parse strings to numbers and other String class operations • Accept command-line arguments V ar i a b l e s ,D a t a T y p e s, a n d S i m p l e I / O 2 CHAPTER JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 25 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The Project: the NameGame Application You’ll use the concepts introduced in this chapter to create this interactive appli- cation. It is interactive because it allows users to enter input. It then processes this input and issues output. Figure 2.1 shows how this application appears when you run it. 26 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r In this simple game, the program prompts the user for a first name. Next, the program responds to the user and asks a last name. The program then proceeds to manipulate the name and show off to the user. In fact, it demonstrates, how- ever basically, most of the concepts behind what an application should be able to do. It provides a user interface, which prompts the user for some information, allows the user to enter this information, processes the information, and outputs the information in a new form for the user to ingest. These basic functions are present in any useful application and are the keys to learning any programming language. Variables and Data Types In this section you learn what variables and data types are and how Java uses them. Variables are basically containers that hold specific types of data. Oddly enough, these specific types of data, such as integers, floating-point numbers, and bytes, are called data types. The data contained by the variable can vary (that’s why it’s called a variable), but the data type cannot change. Variables are used to temporarily store pieces of data that the program makes use of. Think of a folder. A folder holds documents. A person can use the folder by reading the information FIGURE 2.1 This shows two successive runs of the NameGame application. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 26 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. that it holds. This person can also take the document out and put a new one in it that can be used later. In this analogy, the folder acts as the variable, documents act as the data type, and the information in the documents acts as the data. Learning Primitive Data Types A variable must have a data type. A variable’s data type can be a reference data type or a primitive data type. Primitive data types are built into the system. They are not objects. They are specific values that can easily be stored by a computer using a specific amount of memory. If you declare a variable to be of a specific primitive data type, that variable will always hold a value that is of that data type. For example, if you specify variable n to be an int type, n will always hold an integer. Reference data type variables—used for class, interface, and array ref- erences—don’t actually contain the object data. Instead, they hold a reference to the data. In other words, they tell the computer where to find the object’s data in memory. Unlike other languages, primitive data types in Java are system-inde- pendent because Java specifies their size and format. There are eight primitive data types. They are listed in Table 2.1. The four integer types ( byte, short, int, and long) can be positive, negative, or zero. The same is true for the two floating-point types ( float and double). The char type can hold one Unicode character (for example: a, b, c, A, B, C, 7, &, *, and ~). Unicode is a character set that provides a unique number for every character. The boolean type can hold only the values true or false. After you have declared a variable to be of a certain type, it can only hold that specific type of data. 27 C h a p t e r 2 V a r i a b l e s, D a t a T y p e s ,a n d S i m p l e I / O Keyword Description Size byte Byte-size integer 8-bit short Short integer 16-bit int Integer 32-bit long Long integer 64-bit char Single character 16-bit float Single-precision floating point 32-bit double Double-precision floating point 64-bit boolean True or false 1-bit TABLE 2.1 PRIMITIVE D ATA T YPES JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 27 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... exception to the fact that Java is case-sensitive in most cases.) Chapter 2 Because Java considers integer literals, such as 27 to be an int, if you want it to be considered a long, you have to explicitly indicate that The way to do this is by adding the letter L at the end of the number Simply type 27L JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 30 Java Programming for the Absolute Beginner 30 print... good time to put your knowledge of variables to use From this point forward I assume that you already know how to write, compile, and run your Java applications, so here is the source code to the VariableDemo application: Chapter 2 double a, b, c = 2.28, d, e = 1.11; JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 34 Java Programming for the Absolute Beginner 34 This application demonstrates the use of variables—naming,... - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Variables, Data Types, and Simple I/O System.out.println(“The meal costs $” + meal); Chapter 2 public static void main(String args[]) { JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 36 Java Programming for the Absolute Beginner 36 There are different mathematical operations for addition,...JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 28 28 Java Programming for the Absolute Beginner HIN T The primitive data type you use depends upon what the purpose of the variable will be For example, if you wanted to store highly precise scientific calculations, you would probably want to use a... Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Variables, Data Types, and Simple I/O Interpretation Chapter 2 Escape Code JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 32 Java Programming for the Absolute Beginner 32 typed the previous example in your code, the variable myNumber becomes a container that is able to hold integers It does not contain any value until... (long) 27 This number can also be expressed as a byte, short, float, or double by either casting it in a manner similar to the example or for a float or double, you can type 27F for a float or 27D for a double You can also cast a value that is already stored by a variable For example, if x holds an integer value, but you need to express it as a double, you can do it by casting it to a float: (float) x This... TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Variables, Data Types, and Simple I/O You can use lowercase letters when specifying data types for literals For example, you can use the lowercase letter l to specify a long, but you can see how it can be confused with the number 1 27l can be mistaken for 271 quite easily... indicate specific data values Basically, what you type is what you get If you type a 1, Java interprets that to mean the integer value 1 If you type a B, Java determines that to be the character value B If you type the string “Obi-wan Kenobi”, the value of that string literal will be “Obi-Wan Kenobi” You’ve used literals before In the HelloWorld application, the string “Hello, World!” is a literal You can... systems and word processors use these characters differently For example, DOS uses both a carriage return and a newline character, whereas the Mac uses only the carriage return and UNIX uses only the newline character TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 31 31 TA B L E... LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 35 35 public class TipAdder { float meal = 22.50F; float tip = 0.15F * meal; float total = meal + tip; System.out.println(“The 15% tip is $” + tip); System.out.println(“The total bill is $” + total); } } This program performs mathematical . interface, which prompts the user for some information, allows the user to enter this information, processes the information, and outputs the information in a new form for the user to ingest. These. applets. Java- enabled Web browsers typically have a Java console, or window that displays these types of messages. For example, if you’re using Internet Explorer, you can call up the Java console. similar to the example or for a float or double, you can type 27F for a float or 27D for a double. You can also cast a value that is already stored by a variable. For example, if x holds an