Java Reference
In-Depth Information
Enter three words separated by spaces: Welcome to Java
s1 is Welcome
s2 is to
s3 is Java
The
next()
method reads a string that ends with a whitespace character. You can use
the
nextLine()
method to read an entire line of text. The
nextLine()
method reads a
string that ends with the
Enter
key pressed. For example, the following statements read a
line of text.
whitespace character
Scanner input =
new
Scanner(System.in);
System.out.println(
"Enter a line: "
);
String s = input.nextLine();
System.out.println(
"The line entered is "
+ s);
Enter a line: Welcome to Java
The line entered is Welcome to Java
Important Caution
To
avoid input errors
, do not use
nextLine()
after
nextByte()
,
nextShort()
,
nextInt()
,
nextLong()
,
nextFloat()
,
nextDouble()
, or
next()
. The
reasons will be explained in Section 12.11.4, 'How Does
Scanner
Work?'
avoid input errors
4.4.6 Reading a Character from the Console
To read a character from the console, use the
nextLine()
method to read a string and then
invoke the
charAt(0)
method on the string to return a character. For example, the following
code reads a character from the keyboard:
Scanner input =
new
Scanner(System.in);
System.out.print(
"Enter a character: "
);
String s = input.nextLine();
char
ch = s.charAt(
0
);
System.out.println(
"The character entered is "
+ ch);
4.4.7 Comparing Strings
The
String
class contains the methods as shown in Table 4.8 for comparing two strings.
T
ABLE
4.8
Comparison Methods for
String
Objects
Method
Description
equals(s1)
Returns true if this string is equal to string
s1
.
equalsIgnoreCase(s1)
Returns true if this string is equal to string
s1
; it is case insensitive.
compareTo(s1)
Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater
than, equal to, or less than
s1
.
compareToIgnoreCase(s1)
Same as
compareTo
except that the comparison is case insensitive.
startsWith(prefix)
Returns true if this string starts with the specified prefix.
endsWith(suffix)
Returns true if this string ends with the specified suffix.
contains(s1)
Returns true if s1 is a substring in this string.
Search WWH ::
Custom Search