• 沒有找到結果。

Syntax 3.3 : Cast

3.7 Strings

A string is a sequence of characters. Strings are objects of the String class.

Strings can be concatenated, that is, put end to end to yield a new longer string.

String concatenation is denoted by the + operator.

Whenever one of the arguments of the + operator is a string, the other argument is converted to a string.

The concatenation "The total is " + total computes a single string that consists of the string "The total is ", followed by the string equivalent of the number total.

Sometimes you have a string that contains a number, usually from user input. For example, suppose that the string variable input has the value "19". To get the integer value 19, you use the static parseInt method of the Integer class.

int count = Integer.parseInt(input);

// count is the integer 19

To convert a string containing floating-point digits to its floating-point value, use the static parseDouble method of the Double class. For example, suppose input is the string "3.95".

double price = Double.parseDouble(input);

// price is the floating-point number 3.95

The toUpperCase and toLowerCase methods make strings with only upper- or lower-case characters. For example,

String greeting = "Hello";

System.out.println(greeting.toUpperCase());

System.out.println(greeting.toLowerCase());

This code segment prints HELLO and hello. Note that the toUpperCase and toLowerCase methods do not change the original String object greeting. They return new String objects that contain the uppercased and lowercased versions of the original string. In fact, no String methods modify the string object on which they operate. For that reason, strings are called immutable objects.

The substring computes substrings of a string. The call s.substring(start, pastEnd)

returns a string that is made up from the characters in the string s, starting at character start, and containing all characters up to, but not including, the character pastEnd. Here is an example:

String greeting = "Hello, World!";

String sub = greeting.substring(0, 4);

// sub is "Hell"

The substring operation makes a string that consists of four char-acters taken from the string greeting. A curious aspect of the sub-string operation is the numbering of the starting and ending positions. Starting position 0 means “start at the beginning of the string”. For technical reasons that used to be important but are no longer relevant, Java string position numbers start at 0. The first string position is labeled 0, the second one 1, and so on. For example, Figure 5 shows the position numbers in the greeting string.

The position number of the last character (12 for the string "Hello, World!") is always 1 less than the length of the string.

If a string contains the digits of a number, you use the Integer.parseInt or Double.parseDouble method to obtain the number value.

Use the substring method to extract a part of a string.

String positions are counted starting with 0.

Let us figure out how to extract the substring "World". Count characters starting at 0, not 1. You find that W, the 8th character, has position number 7. The first character that you don’t want, !, is the character at position 12 (see Figure 6). Therefore, the appropriate substring command is

String w = greeting.substring(7, 12);

It is curious that you must specify the position of the first character that you do want and then the first character that you don’t want. There is one advantage to this setup. You can easily compute the length of the substring: it is pastEnd - start. For example, the string "World" has length 12 7 5.

If you omit the second parameter of the substring method, then all characters from the starting position to the end of the string are copied. For example,

String tail = greeting.substring(7);

// copies all characters from position 7 on sets tail to the string "World!".

Formatting Numbers

The default format for printing numbers is not always what you would like. For example, consider the following code segment:

int quarters = 2;

int dollars = 3;

double total = dollars + quarters * 0.25; // price is 3.5 final double TAX_RATE = 8.5; // tax rate in percent

double tax = total * TAX_RATE / 100; // tax is 0.2975 System.out.println("Total: $" + total);

System.out.println("Tax: $" + tax);

The output is Total: $3.5 Tax: $0.2975 F i g u r e 5

String Positions

F i g u r e 6

Extracting a Substring

H e l l o , W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11 12

H e l l o , W o r l d !

0 1 2 3 4 5 6 7 8 9

5

10 11 12

 

Advanced Topic 3.5













You may prefer the numbers to be printed with two digits after the decimal point, like this:

Total: $3.50 Tax: $0.30

You can achieve this with the NumberFormat class in the java.text package. First, you must use the static method getNumberInstance to obtain a NumberFormat object.

Then you set the maximum number of fraction digits to 2:

NumberFormat formatter =

NumberFormat.getNumberInstance();

formatter.setMaximumFractionDigits(2);

Then the numbers are rounded to two digits. For example, 0.2875 will be converted to the string "0.29". On the other hand, 0.2975 will be converted to "0.3", not "0.30". If you want trailing zeroes, you also have to set the minimum number of fraction digits to 2:

formatter.setMinimumFractionDigits(2);

Then you use the format method of that object. The result is a string that you can print.

formatter.format(tax)

returns the string "0.30". The statement

System.out.println("Tax: $" + formatter.format(tax));

rounds the value of tax to two digits after the decimal point and prints: Tax: $0.30. The “number instance” formatter is useful because it lets you print numbers with as many fraction digits as desired. If you just want to print a currency value, the getCurrencyInstance method of the NumberFormat class produces a more conve-nient formatter. The “currency instance” formatter generates currency value strings, with the local currency symbol (such as $ in the United States) and the appropriate number of digits after the decimal point (for example, two digits in the United States).

NumberFormat formatter = NumberFormat.getCurrencyInstance();

System.out.print(formatter.format(tax));

// prints "$0.30"

The Java programs that you have constructed 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.

The JOptionPane class has a static method showInputDialog that displays an input dialog (see Figure 7). The user can type any string into the input field and click the “OK” button. Then the show-InputDialog method returns the string that the user entered. You should capture the user input in a string variable. For example, String input =

JOptionPane.showInputDialog("How many nickels do you have?");























相關文件