Wednesday, June 30, 2010

Getting User input in Java with Scanner


Target Audience:Beginners

Java 1.5 has a convenient way to receive user inputs. The Scanner class is a part of java util package. It scans the user inputs and with the help of its various next* methods, the user input can be received directly in desired type ( e.g: int , long or String) .For example, the following code allows a user to read a number from System input as integer type

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Suppose if a file contains a list of numbers which can be converted to long type, then we can read those numbers as following.

Scanner sc = new Scanner(new File("numbers_file"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}

Now we’ll do a very simple example to understand it more. We are going to write a program which receives the user inputs and at the end it prints the sum of the given numbers. the program will print if we give “OK” as the last value and press enter key.

package com.learner.scanner;

import java.util.Scanner;

public class ScannerExample {

public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
double sum = 0.0;

/**
* This is to ask the user to enter a number
*/
System.out.println("Enter numbers to calulate sum.");

/**
* Loop through all input tokens e.g: 3 5 7 ok
*/
while (scanner.hasNext()) {

if (scanner.hasNextDouble()) {
sum += scanner.nextDouble();
} else {

// Exits if OK is gove as input
String str = scanner.next();
if (str.equals("OK"))
break;
else {

// Prints the error message if we give other than 'OK'
System.out.println("Error while running. Please try again");
return;
}
}
}

System.out.println("Sum is : " + sum);
}
}

Compile and run the class.
Refer here for how to compile and run- First Java Program

When the program runs, give following input and press enter 1 3 3 OK . Keep at least one space between tokens ( between numbers and ‘OK’)

The output will be : Sum is : 7.0

Wow. It’s pretty easy and clean. Hope it helps you.

Here is another basic video tutorial of how to use scanner

No comments:

Post a Comment