Java Chapter 4 – Console and File Input
4.1 Console Input
A console program can accept input from the keyboard to allow the user to enter variable values during runtime. The easiest way to get console input in Java is to use the Scanner class. A scanner looks for tokens in the input. A token is a series of characters that ends with whitespace (space, tab, carriage return, or end of file). You need to put import java.util.*; at the top of the program.
myinput.java |
import
java.util.*; |
Output |
Enter your name: |
Here are additional console input commands for the primitive variable types:
int Length = in.nextInt();
byte B = in.nextByte();
short Age = in.nextShort();
long Size = in.nextLong();
double Length = in.nextDouble();
char C = in.next().charAt(0);
The Scanner class also has a some boolean methods shown below.
hasnext.java |
import
java.util.*; |
Output |
Enter a number: |
4.2
File Input
File input must be performed within an exception handler. Notice that the main method throws IOException. Below is an example program that reads in 4 integers using the Scanner class.
finput.java |
import
java.io.*; |
data.txt |
73 42 69 27 |
Output |
73 |
finput2.java |
import
java.io.*; |
data.txt |
Sean 55.4 Davin 90.4 |
Output |
Sean 55.4 |