Java Reference
In-Depth Information
"Welcome to Java".endsWith("v")
returns
false
.
"Welcome to Java".contains("to")
returns
true
.
"Welcome to Java".contains("To")
returns
false
.
Listing 4.2 gives a program that prompts the user to enter two cities and displays them in
alphabetical order.
L
ISTING
4.2
OrderTwoCities.java
1
import
java.util.Scanner;
2
3
public class
OrderTwoCities {
4
public static void
main(String[] args) {
5 Scanner input =
new
Scanner(System.in);
6
7
// Prompt the user to enter two cities
8 System.out.print(
"Enter the first city: "
);
9 String city1 = input.nextLine();
10 System.out.print(
"Enter the second city: "
);
11
input
city1
String city2 = input.nextLine();
input
city2
12
13
if
(city1.compareTo(city2) <
0
)
14 System.out.println(
"The cities in alphabetical order are "
+
15 city1 +
" "
+ city2);
16
else
17 System.out.println(
"The cities in alphabetical order are "
+
18 city2 +
" "
+ city1);
19 }
20 }
compare two cities
Enter the first city: New York
Enter the second city: Boston
The cities in alphabetical order are Boston New York
The program reads two strings for two cities (lines 9, 11). If
input.nextLine()
is replaced
by
input.next()
(line 9), you cannot enter a string with spaces for
city1
. Since a city name
may contain multiple words separated by spaces, the program uses the
nextLine
method to
read a string (lines 9, 11). Invoking
city1.compareTo(city2)
compares two strings
city1
with
city2
(line 13). A negative return value indicates that
city1
is less than
city2
.
4.4.8 Obtaining Substrings
You can obtain a single character from a string using the
charAt
method. You can also
obtain a substring from a string using the
substring
method in the
String
class, as shown
in Table 4.9.
For example,
String message =
"Welcome to Java"
;
String message = message.substring(
0
,
11
) +
"HTML"
;
The string
message
now becomes
Welcome to HTML
.
T
ABLE
4.9
The
String
cla
ss contains the methods for obtaining substrings.
Method
Description
Returns this string's substring that begins with the character at the specified
beginIndex
and extends
to the end of the string, as shown in Figure 4.2.
substring(beginIndex)
substring(beginIndex,
endIndex)
Returns this string's substring that begins at the specified
beginIndex
and extends to the character at index
endIndex - 1
, as shown in Figure 4.2. Note that the character at
endIndex
is not part of the substring.
Search WWH ::
Custom Search