05 Reading
05 Reading
Java provides a number of powerful facilities for reading values from a keyboard or
from a file (java.io). Unfortunately these are rather complicated for first time users.
In Java, a set of related classes are collected together in a package. These can then be
brought into a program by the use of the import statement.
Using Scanner
Recent versions of Java have something called a Scanner to read. Here is how you do
that:
import java.util.*;
class Keyboard {
System.out.println("enter a name");
String name=stdin.next();
System.out.println("now an age");
int age=stdin.nextInt();
stdin.nextLine(); //a stupid thing you have
//to do after reading integers to get a new line
System.out.println("enter another string");
String s=stdin.next();
System.out.println(name+" "+age);
}
}
Older Way
import java.io.*;
class TestInput {
System.out.println("enter a name");
String name=stdin.readLine();
System.out.println("now an age");
int age=Integer.parseInt(stdin.readLine());
System.out.println(name+” “+age);
}
}
Lecture 5 1 of 2 3/25/11
More on Exceptions when Reading
Unfortunately, though, it is still always possible for something to go wrong. What if
you type in something, which isn’t a number? How is it supposed to handle things?
Java will “throw up its hands and abandon what it is doing”.
This is a good thing about Java. However tedious it is to have to consider exceptions
when you write programs and to have programs throw those exceptions when they
fail, it is worse to face the consequences of not considering them. Later we will see
how to deal with exceptions in our classes.
Lecture 5 2 of 2 3/25/11