Java Reference
In-Depth Information
if (name.trim().equals(""))
throw new IllegalArgumentException();
System.out.println("Welcome, " + name);
} catch (IllegalArgumentException e) {
System.err.println("Error: name cannot be blank!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.
Execute the class and watch what happens in Eclipse's console. Try to enter your name. What hap-
pens when you enter a blank name?
How It Works
Here's how it works:
1. System.in , System.out , and System.err all act as normal streams as you've seen before. Note,
however, the use of the InputStreamReader class to make a bridge from System.in (a byte stream)
to a BufferedReader , which expects a character stream. Why do we use BufferedReader instead of
BufferedInputStream here? Because we want to use the readLine method to read in a complete line
of user input. This is one of the valid use cases for InputStreamReader . As an alternative, it is also pos-
sible to make use of a Scanner as seen above, in which case the class would look like follows:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
try(
Scanner sc = new Scanner(System.in);
) {
System.out.println("What is your name, user?");
String name = sc.nextLine();
if (name.trim().equals(""))
throw new IllegalArgumentException();
System.out.println("Welcome, " + name);
} catch (IllegalArgumentException e) {
System.err.println("Error: name cannot be blank!");
}
}
}
2.
Note also that we define two catch blocks: one to catch I/O errors as we've done before, and one
to catch our own thrown exception in case the user enters a blank name.
The reason why both normal output and error streams are provided is not native to Java, but is due
to historical reasons and standardization of command-line I/O in modern operating systems. Both
normal output and error streams are provided to allow users to redirect output to a file, while still
showing error messages on the command line. This concept is not native to Java, but is included for
historical reasons due to the standardization of command-line I/O in modern operating systems.
Search WWH ::




Custom Search