How do I read user input from console using Scanner class?

Bookmark this example!  
Category: java.util, viewed: 4442 time(s).

In JDK 1.5 a java.util.Scanner class was introduce to handle user input in console application. This class enable us to read string, integer, long, etc in the console application.

 
package org.kodejava.example.lang;
 
import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
	
	//
	// Read string input for username
	//
	System.out.print("Username: ");
	String username = scanner.nextLine();
	
	//
	// Read string input for password
	//
	System.out.print("Password: ");
	String password = scanner.nextLine();
	
	//
	// Read an integer input for another challenge
	//
	System.out.print("What is 2 + 2: ");
	int result = scanner.nextInt();
	
	if (username.equals("admin") && password.equals("secret") && result == 4) {
	    System.out.println("Welcome to Java Application");
	} else {
	    System.out.println("Invalid username or password, access denied!");	    
	}
    }
}
 
 
Can't find what you are looking for? Join our FORUMS and ask some questions!
Firefox 2
Google

100 Top & Latest

GetJava Download Button

Locations of visitors to this page
eXTReMe Tracker
visitor stats