Unit 1: Introduction to Java


1.3 Scanner class

Input and output in Java is actually quite complicated.


In Java 5 (1.5) a new class was added to make getting input easier. The Scanner class does this. Later on we'll learn more versatile and efficient (and complicated) ways of I/O.

Note: we are using variables in these programs, but we may not have gone over them in class yet. Make sure that you read the lesson on variables

Scanner is used to get information from the keyboard

How to use Scanner


import java.util.Scanner;

public class Test1{
   public static void main(String[] args) {
   
      Scanner sc=new Scanner(System.in);
	  
	  
      System.out.print("Enter your name: ");
      String name = sc.next();
      
      System.out.print("\nEnter your age: ");
      int age = sc.nextInt();
	  
      System.out.println(name + " is "+ age + "years old.");

   } 
}
1. You must import this class (in the "util" package).




2. You must create a scanner object.
Type it in exactly like this. "System.in" means the keyboard. 
You can also call the object "keyboard" instead of "sc".

3. The Scanner object has methods for reading strings, 
ints, doubles, etc.

NOTE: Important things about scanners

  1. Both "next()" and "nextLine()" will read in text. The difference is that next() only reads one word and will stop at white space while nextLine() will read until the end of the line.
    If you use word = sc.next(); you should put a sc.nextLine(); after it.
    (See this page for more details.)
    In fact, any time you are switching from reading one token at a time (int, double, word) to reading a whole line at a time, you'll probably need to add in the line sc.nextLine(); Try this first when things don't work the way they should.
    Read the Java documenataion on nextLine().

  2. If you type in the wrong data type, your program will crash. e.g. the program has nextInt() and you type in a double or a string.
    The way to fix this is to use the hasNextInt() method.
       if (sc.hasNextInt()) {
          age = sc.nextInt();
       } else {  //optional
          System.out.println("Invalid data input. Using 18 for age");
          age = 18;
       }
    
    This will check that the next "token" is an int before you try to read it.

  3. There are similar methods for other data types: sc.nextDouble() and sc.hasNextDouble() , etc

/* You can use this method to make sure that someone enters an integer.
 * It can be called as follows:
 * 
 *      int age = getInt();
 *  OR
 *      int age = getInt("What is your age?");
 *  
 *  getInt2() is a more compact version that you could use instead of getInt(). 
 *  
 *  If you want to use Scanner elsewhere in your program for other things, 
    then why not just have one scanner?  
 *  Make it a global variable and uncomment the line below, 
    then delete the definition of scanner from the methods.
 */

 // static java.util.Scanner sc = new java.util.Scanner(System.in);

static int getInt() {
	return getInt("");
}

static int getInt(String prompt) {
	if (prompt == null || prompt.length() == 0) prompt = "Please enter an integer:";
	java.util.Scanner sc = new java.util.Scanner(System.in);
	System.out.print(prompt + " ");
	
	boolean inputOK = false;
	int num = 0;
	
	while (! inputOK) {
		if (sc.hasNextInt()) {  //check for int
			num = sc.nextInt();
			inputOK = true;
		} else {
			sc.nextLine();   //remove any junk typed
			System.out.print("You must enter an int: ");				
		}
	}
	return num;
}

static int getInt2(String prompt) {
	if (prompt == null || prompt.length() == 0) prompt = "Please enter an integer:";
	java.util.Scanner sc = new java.util.Scanner(System.in);
	System.out.print(prompt + " ");
	
	while (true) {
		//check for int
		if (sc.hasNextInt())	return sc.nextInt();				

		sc.nextLine();   //remove any junk typed
		System.out.print("You must enter an int: ");					
	}
}

You only ever need one Scanner in a java class. Do not make a new Scanner each time you want to get input. You only have one keyboard, so you only have one Scanner connected to it (to System.in).
Exception: in the example above, I create the scanner in the method so that it doesn't depend on the user remembering to create it elsewhere.

Reading from a text file.

Scanner can read from text files too

File file = new File("MyFile.txt");
Scanner input = new Scanner(file);

This is a NEW Scanner from the one that is connected to the keyboard. This scanner connects to a file.

So ... these two lines make a file object which requires a filename (with its extension).
Then Scanner opens the file and you can read from the file using your variable "input"


Here's how you do the actual reading (assuming a long file):

//read one line at a time, then do something with that line
while (input.hasNextLine()) {
	String line = input.nextLine();
	System.out.println(line);
}
input.close();

BUT... you have to change your method to this

public static void main(String[] args) throws FileNotFoundException {
This is not the ideal way of doing things, but we'll stick with it until we learn try - catch.

Problem! where is the text file located?

With Notepad++, you just put the text file in the same folder as the .java files

BUT when using Eclipse, it is a lot more complicated. I'll have to get back to you on this ...