Sunteți pe pagina 1din 2

Reading values from the keyboard

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 {

public void reading(){


Scanner stdin = new Scanner (System.in);

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 {

public void reading() throws IOException {


BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));

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);
}
}

What is this ‘throws IOException’ thing?


This warns the compiler that something might go wrong in reading, and is required
when using BufferedReader (if you don’t put it in every method that uses it and every
method that uses those methods the compiler will tell you off.)

This is not a problem with Scanner.

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”.

In Java terms, it will throw an exception. Example:


Please type in your age: fred
java.lang.NumberFormatException: fred
at java.lang.Integer.parseInt(Integer.java)
at …
at TestInput.reading(TestInput.java:17)
All of this tells us that the program has been abandoned; it tells us where and why this
has happened.

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

S-ar putea să vă placă și