Page 203 - Introduction to Programming with Java: A Problem Solving Approach
P. 203
Since checking for the empty string is such a common need, Sun provides a method to handle that need. The isEmpty method returns true if the calling string contains the empty string and false otherwise. Fig- ure 5.9’s program uses the isEmpty method as part of an input validation while loop. The while loop forces the user to enter a non-empty name.
Substring Retrieval
Note the two substring methods in Figure 5.8. The one-parameter substring method returns a string that is a subset of the calling-object string, starting at the beginIndex parameter’s position and extending to the end of the calling-object string. The two-parameter substring method returns a string that is a subset of the calling-object string. The returned substring starts at the beginIndex position and extends
5.6 String Methods 169
/*******************************************************************
*
StringMethodDemo.java
Dean & Dean
This program exercises the String class's isEmpty method.
*******************************************************************/
*
*
*
import java.util.Scanner;
{
class
Scanner stdIn = new Scanner(System.in);
String name;
System.out.print("Enter your name: ");
name = stdIn.nextLine();
while (name.isEmpty())
StrAinpgMaetghodDePmoDF Enhancer public static void main(String[] args)
public
{
}
// end StringMethodDemo
}
// end main
}
System.out.print("Invalid entry. You must enter your name: ");
name = stdIn.nextLine();
System.out.println("Hello, " + name + "!");
This checks for the empty string.
{
Sample session:
Enter your name:
Invalid entry. You must enter your name: Virginia Maikweki
The user immediately presses Enter here.
Hello, Virginia Maikweki!
Figure 5.9 StringMethodDemo program exercises various String class methods