Java Concepts 5th Edition and 6th phần 3 potx

111 338 0
Java Concepts 5th Edition and 6th phần 3 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Java Concepts, 5th Edition 14. Assuming the String variable river holds the value “Mississippi”, what is the value of river.substring(1, 2)? Of river.substring(2, river.length() - 3)? PRODUCTIVITY HINT 4.2: Reading Exception Reports You will often have programs that terminate and display an error message, such as Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -4 at java.lang.String.substring (String.java:1444) at Homework1.main(Homework1.java:16) An amazing number of students simply give up at that point, saying “it didn't work”, or “my program died”, without ever reading the error message. Admittedly, the format of the exception report is not very friendly. But it is actually easy to decipher it. When you have a close look at the error message, you will notice two pieces of useful information: 1. The name of the exception, such as StringIndexOutOfBoundsException 2. The line number of the code that contained the statement that caused the exception, such as Homework1.java:16 The name of the exception is always in the first line of the report, and it ends in Exception. If you get a StringIndexOutOfBoundsException, then there was a problem with accessing an invalid position in a string. That is useful information. The line number of the offending code is a little harder to determine. The exception report contains the entire stack trace—that is, the names of all methods that were pending when the exception hit. The first line of the stack trace is the method that actually generated the exception. The last line of the stack trace is a line in main. Often, the exception was thrown by a method that is in the standard 160 161 Chapter 4 Fundamental Data Types Page 39 of 69 Java Concepts, 5th Edition library. Look for the first line in your code that appears in the exception report. For example, skip the line that refers to java.lang.String.substring(String.java:1444) The next line in our example mentions a line number in your code, Homework1.java. Once you have the line number in your code, open up the file, go to that line, and look at it! In the great majority of cases, knowing the name of the exception and the line that caused it make it completely obvious what went wrong, and you can easily fix your error. ADVANCED TOPIC 4.4: Escape Sequences Suppose you want to display a string containing quotation marks, such as Hello, "World"! You can't use System.out.println("Hello, "World"!"); As soon as the compiler reads “Hello, ”, it thinks the string is finished, and then it gets all confused about World followed by two quotation marks. A human would probably realize that the second and third quotation marks were supposed to be part of the string, but a compiler has a one-track mind. If a simple analysis of the input doesn't make sense to it, it just refuses to go on, and reports an error. Well, how do you then display quotation marks on the screen? You precede the quotation marks inside the string with a backslash character. Inside a string, the sequence \” denotes a literal quote, not the end of a string. The correct display statement is, therefore System.out.println("Hello, \"World\"!"); The backslash character is used as an escape character; the character sequence \” is called an escape sequence. The backslash does not denote itself; instead, it is used to encode other characters that would otherwise be difficult to include in a string. Now, what do you do if you actually want to print a backslash (for example, to specify a Windows file name)? You must enter two \ in a row, like this: Chapter 4 Fundamental Data Types Page 40 of 69 Java Concepts, 5th Edition System.out.println("The secret message is in C:\\Temp\\Secret.txt"); This statement prints The secret message is in C:\Temp\Secret.txt Another escape sequence occasionally used is \n, which denotes a newline or line feed character. Printing a newline character causes the start of a new line on the display. For example, the statement System.out.print("*n**n***n"); prints the characters * ** *** on three separate lines. Of course, you could have achieved the same effect with three separate calls to println. Finally, escape sequences are useful for including international characters in a string. For example, suppose you want to print “All the way to San José!”, with an accented letter (é). If you use a U.S. keyboard, you may not have a key to generate that letter. Java uses the Unicode encoding scheme to denote international characters. For example, the é character has Unicode encoding 00E9. You can include that character inside a string by writing \u, followed by its Unicode encoding: System.out.println("All the way to San Jos\u00E9!"); You can look up the codes for the U.S. English and Western European characters in Appendix B, and codes for thousands of characters in reference [1]. ADVANCED TOPIC 4.5: Strings and the Char Type Strings are sequences of Unicode characters (see Random Fact 4.2). Character constants look like string constants, except that character constants are delimited by single quotes: ‘H’ is a character, “H” is a string containing a single character. 161 162 Chapter 4 Fundamental Data Types Page 41 of 69 Java Concepts, 5th Edition You can use escape sequences (see Advanced Topic 4.4) inside character constants. For example, ‘\n’ is the newline character, and ‘\u00E9’ is the character é. You can find the values of the character constants that are used in Western European languages in Appendix B. Characters have numeric values. For example, if you look at Appendix B, you can see that the character ‘H’ is actually encoded as the number 72. When Java was first designed, each Unicode character was encoded as a two-byte quantity. The char type was intended to hold the code of a Unicode character. However, as of 2003, Unicode had grown so large that some characters needed to be encoded as pairs of char values. Thus, you can no longer think of a char value as a character. Technically speaking, a char value is a code unit in the UTF-16 encoding of Unicode. That encoding represents the most common characters as a single char value, and less common or supplementary characters as a pair of char values. The charAt method of the String class returns a code unit from a string. As with the sub-string method, the positions in the string are counted starting at 0. For example, the statement String greeting = "Hello"; char ch = greeting.charAt(0); sets ch to the value ‘H’. However, if you use char variables, your programs may fail with some strings that contain international or symbolic characters. For example, the single character » (the mathematical symbol for the set of integers) is encoded by the two code units ‘\uD835’ and ‘\uDD6B’. If you call charAt(0) on the string containing the single character » (that is, the string “\uD835\uDD6B”), you only get the first half of a supplementary character. Therefore, you should only use char values if you are absolutely sure that you won't need to encode supplementary characters. 162 Chapter 4 Fundamental Data Types Page 42 of 69 Java Concepts, 5th Edition RANDOM FACT 4.2: International Alphabets The English alphabet is pretty simple: upper- and lowercase a to z. Other European languages have accent marks and special characters. For example, German has three umlaut characters (ä, ö, ü) and a double-s character (ß). These are not optional frills; you couldn't write a page of German text without using these characters. German computer keyboards have keys for these characters (see A German Keyboard). This poses a problem for computer users and designers. The American standard character encoding (called ASCII, for American Standard Code for Information Interchange) specifies 128 codes: 52 upper- and lowercase characters, 10 digits, 32 typographical symbols, and 34 control characters (such as space, newline, and 32 others for controlling printers and other devices). The umlaut and double-s are not among them. Some German data processing systems replace seldom-used ASCII characters with German letters: [ \ ] { | } ∼ are replaced with Ä Ö Ü ä ö ü ß. Most people can live without those ASCII characters, but programmers using Java definitely cannot. Other encoding schemes take advantage of the fact that one byte can encode 256 different characters, but only 128 are standardized by ASCII. Unfortunately, there are multiple incompatible standards for using the remaining 128 characters, resulting in a certain amount of aggravation among e-mail correspondents in different European countries. Many countries don't use the Roman script at all. Russian, Greek, Hebrew, Arabic, and Thai letters, to name just a few, have completely different shapes (see The Thai Alphabet). To complicate matters, scripts like Hebrew and Arabic are written from right to left instead of from left to right, and many of these scripts have characters that stack above or below other characters, as those marked with a dotted circle in The Thai Alphabet do in Thai. Each of these alphabets has between 30 and 100 letters, and the countries using them have established encoding standards for them. The situation is much more dramatic in languages that use Chinese script: the Chinese dialects, Japanese, and Korean. The Chinese script is not alphabetic but ideographic—a character represents an idea or thing rather than a single sound. (See A Menu with Chinese Characters; can you identify the characters for soup, 162 163 Chapter 4 Fundamental Data Types Page 43 of 69 Java Concepts, 5th Edition chicken, and wonton?) Most words are made up of one, two, or three of these ideographic characters. Tens of thousands of ideographs are in active use, and China, Taiwan, Hong Kong, Japan, and Korea developed incompatible encoding standards for them. A German Keyboard The Thai Alphabet The inconsistencies among character encodings have been a major nuisance for international electronic communication and for software manufacturers vying for a global market. Between 1988 and 1991 a consortium of hardware and software manufacturers developed a uniform encoding scheme called Unicode that is expressly designed to encode text in all written languages of the world (see reference [1]). In the first version of Unicode, about 39,000 characters were given codes, including 21,000 Chinese ideographs. A 2-byte code (which can encode 163 164 Chapter 4 Fundamental Data Types Page 44 of 69 Java Concepts, 5th Edition over 65,000 characters) was chosen. It was thought to leave ample space for expansion for esoteric scripts, such as Egyptian hieroglyphs and the ancient script used on the island of Java. Java was one of the first programming languages to embrace Unicode. The primitive type char denotes a 2-byte Unicode character. (All Unicode characters can be stored in Java strings, but which ones can actually be displayed depends on your computer system.) A Menu with Chinese Characters Unfortunately, in 2003, the inevitable happened. Another large batch of Chinese ideographs had to be added to Unicode, pushing it beyond the 16-bit limit. Now, some characters need to be encoded with a pair of char values. 4.7 Reading Input The Java programs that you have made so far have constructed objects, called methods, printed results, and exited. They were not interactive and took no user input. In this section, you will learn one method for reading user input. Use the Scanner class to read keyboard input in a console window. Because output is sent to System.out, you might think that you use System.in for input. Unfortunately, it isn't quite that simple. When Java was first designed, not 164 165 Chapter 4 Fundamental Data Types Page 45 of 69 Java Concepts, 5th Edition much attention was given to reading keyboard input. It was assumed that all programmers would produce graphical user interfaces with text fields and menus. System.in was given a minimal set of features—it can only read one byte at a time. Finally, in Java version 5, a Scanner class was added that lets you read keyboard input in a convenient manner. To construct a Scanner object, simply pass the System.in object to the Scanner constructor: Scanner in = new Scanner(System.in); You can create a scanner out of any input stream (such as a file), but you will usually want to use a scanner to read keyboard input from System.in. Once you have a scanner, you use the nextInt or nextDouble methods to read the next integer or floating-point number. System.out.print("Enter quantity: "); int quantity = in.nextInt(); System.out.print("Enter price: "); double price = in.nextDouble(); When the nextInt or nextDouble method is called, the program waits until the user types a number and hits the Enter key. You should always provide instructions for the user (such as “Enter quantity:”) before calling a Scanner method. Such an instruction is called a prompt. The nextLine method returns the next line of input (until the user hits the Enter key) as a String object. The next method returns the next word, terminated by any white space, that is, a space, the end of a line, or a tab. System.out.print("Enter city: "); String city = in.nextLine(); System.out.print("Enter state code: "); String state = in.next(); Here, we use the nextLine method to read a city name that may consist of multiple words, such as San Francisco. We use the next method to read the state code (such as CA), which consists of a single word. 165 Chapter 4 Fundamental Data Types Page 46 of 69 Java Concepts, 5th Edition Here is an example of a class that takes user input. This class uses the CashRegister class and simulates a transaction in which a user purchases an item, pays for it, and receives change. We call this class CashRegisterSimulator, not CashRegisterTester. We reserve the Tester suffix for classes whose sole purpose is to test other classes. ch04/cashregister/CashRegisterSimulator.java 1 import java.util.Scanner; 2 3 /** 4 This program simulates a transaction in which a user pays for an item 5 and receives change. 6 */ 7 public class CashRegisterSimulator 8 { 9 public static void main(String[] args) 10 { 11 Scanner in = new Scanner(System.in); 12 13 CashRegister register = new CashRegister(); 14 15 System.out.print(“Enter price: ”); 16 double price = in.nextDouble(); 17 register.recordPurchase(price); 18 19 System.out.print(“Enter dollars: ”); 20 int dollars = in.nextInt(); 21 System.out.print(“Enter quarters: ”); 22 int quarters = in.nextInt(); 23 System.out.print(“Enter dimes: ”); 24 int dimes = in.nextInt(); 165 166 Chapter 4 Fundamental Data Types Page 47 of 69 Java Concepts, 5th Edition 25 System.out.print(“Enter nickels: ”); 26 int nickels = in.nextInt(); 27 System.out.print(“Enter pennies: ”); 28 int pennies = in.nextInt(); 29 register.enterPayment(dollars, quarters, dimes, nickels, pennies); 30 31 System.out.print(“Your change: ”); 32 System.out.println(register. giveChange 33 } 34 } Output Enter price: 7.55 Enter dollars: 10 Enter quarters: 2 Enter dimes: 1 Enter nickels: 0 Enter pennies: 0 Your change: 3.05 SELF CHECK 15. Why can't input be read directly from System.in? 16. Suppose in is a Scanner object that reads from System.in, and your program calls String name = in.next(); What is the value of name if the user enters John Q. Public? ADVANCED TOPIC 4.6: Formatting Numbers The default format for printing numbers is not always what you would like. For example, consider the following code segment: double total = 3.50; final double TAX_RATE = 8.5; // Tax rate in percent 166 167 Chapter 4 Fundamental Data Types Page 48 of 69 [...]... OBJECTS, AND METHODS INTRODUCED IN THIS CHAPTER 170 171 java. io.PrintStream printf java. lang.Double parseDouble java. lang.Integer parseInt toString MAX_VALUE MIN_VALUE Chapter 4 Fundamental Data Types Page 53 of 69 Java Concepts, 5th Edition java. lang.Math E PI abs acos asin atan atan2 ceil cos exp floor log max min pow round sin sqrt tan toDegrees toRadians java. lang.String format substring java. lang.System... Moreover, if s1, s2, and s3 are integers, you must divide by 3. 0 to avoid integer division: Chapter 4 Fundamental Data Types Page 68 of 69 Java Concepts, 5th Edition (s1 + s2 + s3) / 3. 0 10 2 x +y 2 11 x is a number, not an object, and you cannot invoke methods on numbers 12 No—the println method is called on the object System.out 13 s is set to the string Agent5 14 The strings “i” and “ssissi” 15 The... Example 1. 23 followed by spaces 001. 23 +1. 23 (1. 23) 12 ,30 0 1.23E+1 The format method of the String class is similar to the printf method However, it returns a string instead of producing output For example, the call Chapter 4 Fundamental Data Types 168 169 Page 50 of 69 Java Concepts, 5th Edition String message = String.format("Total:%5.2f", total); sets the message variable to the string “Total: 3. 50”... System.out.println("Expected: 3" ); } } 176 177 ★★★ Exercise P4.12 Write a program that reads in an integer and breaks it into a sequence of individual digits in reverse order For example, the input 1 638 4 is displayed as 4 8 3 6 1 You may assume that the input has no more than five digits and is not negative Chapter 4 Fundamental Data Types Page 63 of 69 Java Concepts, 5th Edition Define a class DigitExtractor:... in java. math.BigDecimal add multiply subtract java. math.BigInteger add multiply subtract java. util.Scanner next nextDouble nextInt nextLine javax.swing.JOptionPane showInputDialog showMessageDialog Chapter 4 Fundamental Data Types Page 54 of 69 Java Concepts, 5th Edition REVIEW EXERCISES ★★ Exercise R4.1 Write the following mathematical expressions in Java 2 1 s = s 0 + v 0 t +2 gt G = 4π a 2 2 3 (... 1 730 ) and prints the number of hours and minutes between the two times Here is a sample run User input is in color 177 178 Please enter the first time: 0900 Please enter the second time: 1 730 8 hours 30 minutes Extra credit if you can deal with the case where the first time is later than the second time: Please enter the first time: 1 730 Chapter 4 Fundamental Data Types Page 64 of 69 Java Concepts, 5th. .. Explain the differences between 2, 2.0, ‘2’, “2”, and “2.0” ★ Exercise R4.10 Explain what each of the following two program segments computes: int x = 2; int y = x + x; and String s = "2"; String t = s + s; Chapter 4 Fundamental Data Types 172 Page 56 of 69 Java Concepts, 5th Edition 172 ★★ Exercise R4.11 True or false? (x is an int and s is a String) 1 73 a Integer.parseInt(“” + x) is the same as x b... Divide y by 19 and call the remainder a Ignore the quotient 3 Divide y by 100 to get a quotient b and a remainder c 4 Divide b by 4 to get a quotient d and a remainder e 5 Divide 8 * b + 13 by 25 to get a quotient g Ignore the remainder 6 Divide 19 * a + b − d − g + 15 by 30 to get a remainder h Ignore the quotient 7 Divide c by 4 to get a quotient j and a remainder k 8 Divide a + 11 * h by 31 9 to get... easier to read and maintain 8 Assignment to a variable is not the same as mathematical equality 9 The ++ and operators increment and decrement a variable 10 If both arguments of the / operator are integers, the result is an integer and the remainder is discarded 11 The % operator computes the remainder of a division Chapter 4 Fundamental Data Types Page 52 of 69 Java Concepts, 5th Edition 12 The... values of this pair @return the sum of the first and second values Chapter 4 Fundamental Data Types 174 175 Page 59 of 69 Java Concepts, 5th Edition */ public double getSum() { } } Then implement a class PairTester that constructs a Pair object, invokes its methods, and prints the results ★ Exercise P4.5 Define a class DataSet that computes the sum and average of a sequence of integers Supply methods . 162 1 63 Chapter 4 Fundamental Data Types Page 43 of 69 Java Concepts, 5th Edition chicken, and wonton?) Most words are made up of one, two, or three of these ideographic characters. Tens of thousands. characters, 10 digits, 32 typographical symbols, and 34 control characters (such as space, newline, and 32 others for controlling printers and other devices). The umlaut and double-s are not. of 69 Java Concepts, 5th Edition RANDOM FACT 4.2: International Alphabets The English alphabet is pretty simple: upper- and lowercase a to z. Other European languages have accent marks and special

Ngày đăng: 12/08/2014, 19:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan