⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch5.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 4 页
字号:
you need variables in a program is to hold the results of a calculation.In this case, you can think of the word <TT>tax</TT> as a kindof digital bucket into which the program dumps the result of itssales tax calculation. When you need the value stored in <TT>tax</TT>,you can just reach in and take it out-figuratively speaking, ofcourse. As an example, to determine the total cost of a $12.00purchase, plus the sales tax, you might write a line like this:<BLOCKQUOTE><PRE>total = 12 + tax;</PRE></BLOCKQUOTE><P>In this line, the word <TT>total</TT> is yet another variable.After the computer performs the requested calculation, the variable<TT>total</TT> will contain the sum of 12 and whatever value isstored in <TT>tax</TT>. For example, if the value 0.72 is storedin <TT>tax</TT>, after the calculation, <TT>total</TT> would beequal to 12.72.<P>Do you see another place where a variable is necessary? How aboutthe hard-coded value 12? Such a hard-coded value makes a programpretty useless because every person that comes into your storeto buy something isn't going to spend exactly $12.00. Becausethe amount of each customer's purchase will change, the valueused in your sales tax calculation must change, too. That meansyou need another variable. How about creating a variable named<TT>purchase</TT>? With such a variable, you can rewrite the calculationslike this:<BLOCKQUOTE><PRE>tax = purchase * SALESTAX;total = purchase + tax;</PRE></BLOCKQUOTE><P>Now you can see how valuable variables can be. Every value inthe preceding lines is represented by a variable. (Although you'reusing <TT>SALESTAX</TT> as a symbolic constant, because of Java'scurrent lack of true constants, it's really a variable, too.)All you have to do to get the total to charge your customer isplug the cost of his purchase into the variable <TT>purchase</TT>,something you'll see how to do in <A HREF="ch6.htm" >Chapter 6</A> &quot;Simple Inputand Output.&quot;<P>Math-savvy readers may have already figured that the precedingtwo lines can be easily simplified into one, like this:<BLOCKQUOTE><PRE>total = purchase + (purchase * SALESTAX);</PRE></BLOCKQUOTE><P>This revised line of code, however, is not as easy to understandas the original two lines were. In programming, you must constantlydecide between longer, simpler code and shorter, more complexcode. I tend to go for the longer, easy-to-understand approach,except when the longer code might bog down the program.<H2><A NAME="NamingConstantsandVariables"><FONT SIZE=5 COLOR=#Ff0000>Naming Constants and Variables</FONT></A></H2><P>The first computer languages were developed by mathematicians.For that reason, the calculations and the variables used in thosecalculations were modeled after the types of equations mathematicianswere already accustomed to working with. For example, in the olddays, the lines in your tax program might have looked like this:<BLOCKQUOTE><PRE>a = b * c;d = b + a;</PRE></BLOCKQUOTE><P>As you can see, this type of variable-naming convention left alot to be desired. It's virtually impossible to tell what typeof calculations are being performed. In order to understand theirown programs, programmers had to use tons of comments mixed inwith their source code so they could remember what the heck theywere doing from one programming session to the next. Such a sectionof source code in Java might look like Listing 5.1.<HR><BLOCKQUOTE><B>Listing 5.1&nbsp;&nbsp;LST5_1.TXT: An Example of Mathematician'sVariables.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>// Calculate the amount of sales tax.a = b * c;// Add the sales tax to the purchase amount.d = b + a;</PRE></BLOCKQUOTE><HR><P>Although adding comments to the program lines helps a little,the code is still pretty confusing, because you don't really knowwhat the variables <TT>a</TT>, <TT>b</TT>, <TT>c</TT>, and <TT>d</TT>stand for. After a while (probably when mathematicians weren'tthe only programmers), someone came up with the idea of allowingmore than one character in a variable name, which would enablethe programmer to create mathematical expressions that read morelike English. Thus, the confusing example above would be writtenas Listing 5.2.<HR><BLOCKQUOTE><B>Listing 5.2&nbsp;&nbsp;LST5_2.TXT: Using English-like VariableNames.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>// Calculate the amount of sales tax.tax = purchase * SALESTAX;// Add the sales tax to the purchase amount.total = purchase + tax;</PRE></BLOCKQUOTE><HR><P>By using carefully chosen variable names, you can make your programsself documenting, which means that the program lines themselvestell whoever might be reading the program what the program does.If you strip away the comments from the preceding example, youcan still see what calculations are being performed.<P>Of course, there are rules for choosing constant and variablenames (also known as identifiers because they identify a programobject). You can't just type a bunch of characters on your keyboardand expect Java to accept them. First, every Java identifier mustbegin with one of these characters:<BLOCKQUOTE>A-Z<BR>a-z<BR>_ <BR>$</BLOCKQUOTE><P>The preceding characters are any uppercase letter from <TT>A</TT>through <TT>Z</TT>, any lowercase letter from <TT>a</TT> through<TT>z</TT>, an underscore, and the dollar sign.<P>Following the first character, the rest of the identifier canuse any of these characters:<BLOCKQUOTE>A-Z<BR>a-z<BR>_ <BR>$<BR>0-9</BLOCKQUOTE><P>As you may have noticed, this second set of characters is verysimilar to the first. In fact, the only difference is the additionof the digits from <TT>0</TT> through <TT>9</TT>.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Java identifiers can also use Unicode characters above the hexadecimal value of 00C0. If you don't know about Unicode characters, don't panic; you won't be using them in this book. Briefly put, Unicode characters expand the symbols that can be used in a character set to include characters that are not part of the English language.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Using the rules given, the following are valid identifiers ina Java program:<BLOCKQUOTE><PRE>numbernumber2amount_of_sale$amount</PRE></BLOCKQUOTE><P>The following identifiers are not valid in a Java program:<BLOCKQUOTE><PRE>1numberamount of sale&amp;amountitem#</PRE></BLOCKQUOTE><H2><A NAME="ExampleCreatingYourOwnIdentifiers"><FONT SIZE=5 COLOR=#Ff0000>Example: Creating Your Own Identifiers</FONT></A></H2><P>Suppose that you're now ready to write a program that calculatesthe total number of parking spaces left in a parking garage. Youknow that the total number of spaces in the garage is 100. Youfurther know that the vehicles in the garage are classified ascars, trucks, and vans. The first step is to determine which valueswould be good candidates for constants. Because a constant shouldrepresent a value that's not likely to change from one programrun to another, the number of vehicles that the garage can holdwould make a good constant. Thinking hard (someone smell woodburning?), you come up with an identifier of <TT>TOTALSPACES</TT>for this value. In Java, the constant's definition looks likethis:<BLOCKQUOTE><PRE>final int TOTALSPACES = 100;</PRE></BLOCKQUOTE><P>In this line, the keyword <TT>int</TT> represents the data type,which is integer. You should be able to understand the rest ofthe line.<P>Now, you need to come up with the mathematical formula that'llgive you the answer you want. First, you know that the total numberof vehicles in the garage is equal to the sum of the number ofcars, trucks, and vans in the garage. Stating the problem in thisway not only clarifies what form the calculation must take, butalso suggests a set of good identifiers for your program. Thoseidentifiers are <TT>cars</TT>, <TT>trucks</TT>, <TT>vans</TT>,and <TT>total_vehicles</TT>. So, in Java, your first calculationlooks like this:<BLOCKQUOTE><PRE>total_vehicles = cars + trucks + vans;</PRE></BLOCKQUOTE><P>The next step is to subtract the total number of vehicles fromthe total number of spaces that the garage holds. For this calculation,you need only one new identifier to represent the remaining spaces,which is the result of the calculation. Again, stating the problemleads to the variable name, which might be <TT>remaining_spaces</TT>.The final calculation then looks like this:<BLOCKQUOTE><PRE>remaining_spaces = TOTALSPACES - total_vehicles;</PRE></BLOCKQUOTE><H2><A NAME="DataTypes"><FONT SIZE=5 COLOR=#Ff0000>Data Types</FONT></A></H2><P>In attempting to give you a quick introduction to constants andvariables, the preceding sections skipped over a very importantattribute of all constants and variables: data type. You may remembermy mentioning two data types already, these being floating point(represented by the <TT>float</TT> keyword) and integer (representedby the <TT>int</TT> keyword). Java has eight different data types,all of which represent different kinds of values in a program.These data types are <TT>byte</TT>, <TT>short</TT>, <TT>int</TT>,<TT>long</TT>, <TT>float</TT>, <TT>double</TT>, <TT>char</TT>,and <TT>boolean</TT>. In this section, you'll learn what kindsof values these various data types represent.<H3><A NAME="IntegerValues">Integer Values</A></H3><P>The most common values used in computer programs are integers,which represent whole number values such as 12, 1988, and -34.Integer values can be both positive or negative, or even the value0. The size of the value that's allowed depends on the integerdata type you choose. Java features four integer data types, whichare <TT>byte</TT>, <TT>short</TT>, <TT>int</TT>, and <TT>long</TT>.Although some computer languages allow both signed and unsignedinteger values, all of Java's integers are signed, which meansthey can be positive or negative. (Unsigned values, which Javadoes not support, can hold only positive numbers.)<P>The first integer type, <TT>byte</TT>, takes up the least amountof space in a computer's memory. When you declare a constant orvariable as <TT>byte</TT>, you are limited to values in the range-128 to 127. Why would you want to limit the size of a value inthis way? Because the smaller the data type, the faster the computercan manipulate it. For example, your computer can move a <TT>byte</TT>value, which consumes only eight bits of memory, much faster thanan <TT>int</TT> value, which, in Java, is four times as large.<P>In Java, you declare a <TT>byte</TT> value like this:<BLOCKQUOTE><PRE>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -