Interactively communicating with the user
We’ll begin by writing a very simple program that asks the user for their name and then prints a personalized greeting.
import java.io.*;
class PersonalHello {
public static void main (String args[])
{
byte name[] = new byte[100];
int bytesRead = 0;
System.out.println("What is your name?");
try {
bytesRead = System.in.read(name);
System.out.print("Hello ");
System.out.write(name, 0, bytesRead);
}
catch (IOException ex) {
System.out.print("I'm Sorry. I didn't catch your name.");
}
}
}
In code that does any significant input or output you’ll want to begin by importing all the various java.io classes. import.java.io.*;
does this and is as ubiquitous in Java applications as #include <stdio.h>
is in C programs.
Most of the reading and writing you do in Java will be done with bytes. (As you’ll see later there are also ways to read text files directly into Strings.) Here we’ve started with an array of bytes that will hold the user’s name.
First we print a query requesting the user’s name. Then we read the user’s name using the System.in.read()
method. This method takes a byte array as an argument, and places whatever the user types in that byte array. Then, like before, we print “Hello.” Finally we print the user’s name.
The program doesn’t actually see what the user types until he or she types a carriage return. This gives the user the chance to backspace over and delete any mistakes. Once the return key is pressed, everything in the line is placed in the array.
What happens if the user types more than 100 characters of text before hitting a carriage return? In many programming languages this would lead to a rather nasty program crash. It’s also the sort of bug that often gets out the door in a shipping product since programmers often fail to test their programs against extreme inputs. However Java has been programmed a little more safely. System.in.read()
won’t read past the end of the array even though we didn’t explicitly check to make sure the input was sufficiently small. My guess is that the System.in.read()
method internally checks the length of the array it’s been passed using the name.length property.