Difference between revisions of "Input using Scanner"

From CompSciWiki
Jump to: navigation, search
(Made example 4 a full working example)
m (improt and comiler corrected)
Line 16: Line 16:
 
When using Scanner with TextPad, make sure the "Capture Output" option for running your java application (Click on Configure -> Tools -> Run Java Application) is turned '''off''. This enables the input to be read properly from a DOS window. If Capture Output is left on, you will get an error when running your java program.
 
When using Scanner with TextPad, make sure the "Capture Output" option for running your java application (Click on Configure -> Tools -> Run Java Application) is turned '''off''. This enables the input to be read properly from a DOS window. If Capture Output is left on, you will get an error when running your java program.
  
Also remember to add the line <code>import java.util.Scanner</code> at the top of your program. This improt statement tells the Java comiler where to find the Scanner files.   
+
Also remember to add the line <code>import java.util.Scanner</code> at the top of your program. This import statement tells the Java compiler where to find the Scanner files.   
  
 
==Declaring a Scanner==
 
==Declaring a Scanner==

Revision as of 11:59, 1 December 2011

COMP 1010 Home > Java Fundamentals


Introduction

Console.png
We already know how to retrieve input from the user using JOptionPane.showInputDialog. That gives a String input. The Scanner class[[1]] can be used with this input to extract ints and doubles from the String. This is great, but sometimes you want to read from the console window instead (much like doing output with System.out.println instead of with JOptionPane.showMessageDialog). The Scanner class[[2]] also enables us to read directly from System.in. Plus, as the course progresses, Scanner gives options to make entering large amount of data (e.g., from files) much easier than JOptionPane.

See Gaddis Chapter 2.13 (page 84) for more information.


Technical Notes on Scanner and TextPad

When using Scanner with TextPad, make sure the "Capture Output" option for running your java application (Click on Configure -> Tools -> Run Java Application) is turned 'off. This enables the input to be read properly from a DOS window. If Capture Output is left on, you will get an error when running your java program.

Also remember to add the line import java.util.Scanner at the top of your program. This import statement tells the Java compiler where to find the Scanner files.

Declaring a Scanner

In the main method, you must begin by using this line of code: Scanner source=new Scanner (...).. At the start of the course this line is rather difficult to explain. If you're interested, it means you are creating an object of the Scanner class (named source), and this newly created object is connected to whatever ... represents. If ... is the name of a String identifier, source will get input from that String. If ... is System.in, source will get input from the keyboard. This line of code essentially sets you up to use a String or System.in to input data that will be processed by the Scanner object's methods. In the rest of this section we will assume the input comes from System.in, since there are more problems that can arise, but the methods like nextInt and nextDouble apply just as well when parsing an input String using Scanner.

Example of using Scanner to get input from a JOptionPane

import javax.swing.JOptionPane ; 
import java.util.Scanner ;

public class ScannerExample1 { 
    public static void main (String[] args) { 
        String input = JOptionPane.showInputDialog("Enter ...") ;
        Scanner source = new Scanner(input) ; 
        ...
    } 
}

Example of using Scanner to get input from the console

import java.util.Scanner;

public class ScannerExample2 { 
    public static void main (String[] args) { 
        Scanner keyboard= new Scanner(System.in); 
        ...
    } 
}

Using Scanner for input

To use Scanner, we can simply tell it to read from the user whatever source type we want. In the following example, we ask the user to enter a number between 1 and 100. Using Scanner class we wait for the user to enter an integer and the press return.

Let's get an integer value from the console

import java.util.Scanner;
public class Example3 {
	public static void main(String args[]){
		int num;
		Scanner keyboard= new Scanner(System.in); 
	        System.out.print("Please enter a number between 1 and 100: ");
	        num = keyboard.nextInt();
	        System.out.println("You entered the number: " + num);
	}
}
C:\>javac Example3.java
C:\>java Example3
Please enter a number between 1 and 100: 66
You entered the number: 66
C:\>

keyboard.nextInt()is responsible for getting the Integer value the user entered back to your program and storing it in the variable num. The scanner class handles expects the user to enter an Integer value, if the user does not your program will crash, as seen in the follow output:

C:\>javac Example3.java
C:\>java Example3
Please enter a number between 1 and 100: fred
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:840)
	at java.util.Scanner.next(Scanner.java:1461)
	at java.util.Scanner.nextInt(Scanner.java:2091)
	at java.util.Scanner.nextInt(Scanner.java:2050)
	at InputDialog.main(Example3.java:7)

How to get other data types from the console

  • nextDouble: similar to nextInt, except reads a double into a double variable (if available):
newDouble = keyboard.nextDouble();
  • nextLine: returns the next line from the user (i.e., all text included until the user hits enter). Note that nextLine returns a String.
String line = keyboard.nextLine():


Warning 24.png Dangers with nextLine

Remember that nextLine returns all the text until the user hits enter. This might cause a problem if you have previously read input from the user, as the scanner could return a blank input indicating that the remainder of the line after the previous input was empty. This is stupid, I know.


More Scanner Methods: Using hasNext methods

As the course progresses we will likely introduce more Scanner methods. If you're reading this section at the start of the term, just leave this next example until you need it later.

For example, in the context of multiple inputs and loops, it will often be useful to use the "hasNext" functions.

For instance, consider this small loop:

import java.util.Scanner;
public class Example4 {
	public static void main(String args[]){
		Scanner keyboard = new Scanner (System.in);
		String nextToken;
		
		while ( keyboard.hasNext() ) {
		    nextToken = keyboard.next();
		    if (nextToken.charAt(0) == 'A') {
		       System.out.println(nextToken);
		    }
		}
	}
}
C:\>javac Example4.java
C:\>java Example4
Aardvark Car Racoon Ameoba Antelope Alligator
Aardvark
Ameoba
Antelope
Alligator

This loop successively reads all the tokens of the input into a variable called nextToken. The loop then prints it out if it starts with the letter 'A'. The important thing to take out of this example is that the loop will continue to execute until there is no more input in the file. You no longer need to worry about null and other such issues.

There’s also hasNext, hasNextInt and hasNextDouble methods. These work like hasNextLine, except the ask if the next thing in the input stream is the right type. For instance, if the input stream is “ABC”, then hasNextInt will return false: the next thing on the input stream cannot be interpreted as an int.

Previous Page: Input using JOptionPane Next Page: Variables