# Java Programming for absolute beginner- P3

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:20

0
65
lượt xem
9

## Java Programming for absolute beginner- P3

Mô tả tài liệu

Java Programming for absolute beginner- P3:Hello and welcome to Java Programming for the Absolute Beginner. You probably already have a good understanding of how to use your computer. These days it’s hard to find someone who doesn’t, given the importance of computers in today’s world. Learning to control your computer intimately is what will separate you from the pack! By reading this book, you learn how to accomplish just that through the magic of programming.

Chủ đề:

Bình luận(0)

Lưu

## Nội dung Text: Java Programming for absolute beginner- P3

4. JavaProgAbsBeg-01.qxd 2/25/03 8:12 AM Page 21 21 Chapter 1 FIGURE 1.7 Getting Started There is no main() method, so it cannot be run as an application. 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: HelloWeb Applet HelloWeb Applet 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. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
14. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 31 31 TA B L E 2 . 3 CHARACTER ESCAPE CODES Chapter 2 Escape Code Interpretation \’ Single quotation mark \” Double quotation mark \b Backspace Variables, Data Types, and Simple I/O \f Form feed (page break) \n Newline character \r Carriage return \t Tab Naming Variables There are specific syntax rules that you must follow when naming variables. The compiler needs to know when you are referring to variables and doesn’t want to mix them up with anything else. That’s why these rules are in place. Java variable names can start with letters, underscores (_), or dollar signs ($). They cannot start with a number or the compiler will assume it is a number literal. Any characters that follow the first character can be any letter, number, underscore, or dollar sign. None of the following characters can be used when naming variables: #%&’()*+,-./:;?@[\]^`{|}~. Aside from these rules there are some naming conventions you should stick to so that your code is readable. Variable names typically start with a lowercase letter. Subsequent letters are lowercase unless they start a new “word,” such as myNum- ber, numSeconds, or costPerUnit. It is also a good idea to choose a name that is descriptive of the data it holds. It makes readability so much better. Keep all this in mind when naming your variables. Declaring and Assigning Values to Variables In this section, you will learn about declaring variables and assigning values to them in more detail. Declaring a variable is creating a variable by specifying its name and data type. For example if you wanted to declare a variable that will be used to hold integers, you could do it by typing the following: int myNumber; This declares a variable of type int named myNumber. Note that the syntax for declaring a variable is the data type followed by the name of the variable. If you TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 15. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 32 32 typed the previous example in your code, the variable myNumber becomes a con- tainer that is able to hold integers. It does not contain any value until it is Java Programming for the Absolute Beginner assigned. Assigning a value to a variable is making the variable hold specific data. A variable remains unusable until it contains data. If the compiler is able to see that a variable might not be initialized, or assigned its initial value, it gives you an error message. Now that you have declared your variable, you can assign the literal 27 to it by typing the following: MyNumber = 27; This puts the integer 27 into the variable myNumber. Note that the syntax for this is the variable name followed by the assignment operator (the equals sign =), fol- lowed by the value being assigned to the variable. Anytime the code refers to myNumber, it will find its contents to be 27 until the variable is reassigned a new value. It can be reassigned different values as many times as you want, but it must always contain an integer. The following snippet of code demonstrates that a variable can be assigned different values: myNumber = 1; // The value of myNumber is now 1. myNumber = 4; // The value of myNumber is now 4. Expressions to the right of the assignment operator don’t necessarily have to be literals. You can assign the value of one variable to another variable. For exam- ple, assume myNumber and myOtherNumber are both integers and myNumber already has its value. The following line assigns the value stored in myOtherNumber to the myNumber variable. MyNumber = myOtherNumber; You can declare and assign the initial value to a variable on one single line if you choose to do so. To declare the myNumber variable and assign it the number 27 on only one line, you type: int myNumber = 27; This line declares an int variable called myNumber and assigns it the value 27 all on one single line. This can be useful if you know what the initial value of your variable will be. Variables inherently can contain any value specific to the data type, so you should never assume the value of a variable when writing your pro- grams. It might be okay to assume the value of a variable after you have just assigned it a value, but that is not a good practice. You should always treat a vari- able in such a way that you might not know its contents. You should only assume what the data type of the variable is. If you need to use a specific value in your program, just use a literal. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 16. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 33 33 You can also declare multiple variables on a single line: Chapter 2 double a, b, c = 2.28, d, e = 1.11; The previous line declares five double variables named a, b, c, d, and e. When declaring multiple variables on a single line of code, the data type appears to the left of the variable list just as if it were one variable. The variable names, sepa- rated by commas, are listed to the right of the data type. You should also notice Variables, Data Types, and Simple I/O that I assigned values to two of the variables (c and e). Now is a 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: /* * VariableDemo * Demonstrates the declaration and assignment of variables */ public class VariableDemo { public static void main(String args[]) { //Declare an int int myNumber; //Assign a value myNumber = 43; //Print out the value of the variable System.out.println(“myNumber = “ + myNumber); //Do other stuff with variables double myDouble = 4.0; char c1 = ‘?’; boolean happy = true, sad = false; int myOtherNumber = myNumber; System.out.println(“myDouble = “ + myDouble); System.out.println(“c1 = “ + c1); System.out.println(“happy = “ + happy); System.out.println(“sad = “ + sad); System.out.println(“myOtherNumber = “ + myOtherNumber); } } TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 17. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 34 34 This application demonstrates the use of variables—naming, declaring, and assigning values to them. Feel free to write, rewrite, and modify this program Java Programming for the Absolute Beginner until you get a good feel for working with variables. There is some syntax in this program that you might be unfamiliar with. When you print the value of your variables, you used the System.out.println() method in a slightly different way than before: System.out.println(“myNumber = “ + myNumber); This line prints “myNumber = 43“ when you run the program as it is listed previ- ously. This appends the value of myNumber to the string literal “myNumber = “ and prints the result. You learn more about string operations in the “Strings and String Operations” section later in this chapter. Figure 2.3 shows the output. FIGURE 2.3 This is the output of the VariableDemo application. Working with Numbers In this section, you learn how Java handles numbers. You learn how to use math- ematical operations on numerical variables. I also go over operator precedence and you write an application that applies these concepts. The TipAdder Program Now you will write a program that calculates a 15 percent tip to give to your waiter or waitress after a nice meal, assuming he or she wasn’t rude of course. Here is a listing of the source code: /* * TipAdder * Demonstrates simple floating point math and importance of precision */ TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 18. JavaProgAbsBeg-02.qxd 2/25/03 8:13 AM Page 35 35 public class TipAdder { public static void main(String args[]) { Chapter 2 float meal = 22.50F; float tip = 0.15F * meal; float total = meal + tip; System.out.println(“The meal costs$” + meal); Variables, Data Types, and Simple I/O System.out.println(“The 15% tip is $” + tip); System.out.println(“The total bill is$” + total); } } This program performs mathematical operations on floating-point numbers. Based on what you’ve learned so far, this application should not be difficult to understand. The only new concept introduced here is the use of mathematical operations. The following line declares the variable meal and assigns it the initial value 22.50. Remember that the letter F specifies the literal 22.50F to be a float: float meal = 22.50F; On the next line, tip is declared to be a float and is immediately assigned its intended value–15% of the cost of the meal: float tip = 0.15F * meal; This mathematical operation multiplies the literal 15.0F by the value stored in the meal variable. The result of this operation is stored in the tip variable. The next line of code calculates the total cost of your dining experience by adding tip to meal and storing the result in total. After that, the application pro- ceeds to issue messages to the user indicating the cost of the meal, the tip amount, and the result of its total meal cost calculation. Figure 2.4 shows what a run of this application looks like: FIGURE 2.4 The TipAdder application in action. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.