Sunday, June 26, 2011

Read User Input with Scanner Class in Java!

This snippet will allow you to read user's input when they write in the console. This method uses the Scanner class, which is my favorite way of doing instead of using the Buffered Reader, with the Scanner, you can also read from a file.

It is very easy and elegent too ..!!


import java.util.Scanner;

/**
 * The Class ReadUserInput.
 *
 * @author Varra
 * @version 1.0
 */
public class ReadUserInput
{
   
    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args)
    {
       
        Scanner sc = new Scanner(System.in); // Creates the scanner and tells it
        // to read from the keyboard(System.in)
       
        System.out.println("Enter your name.");
        final String name = sc.nextLine(); // Sets name equal to user's input
        // if you just call the "next" method, the Scanner will read up to the
        // first space.
        System.out.println("Hello " + name);// Greets the user
       
    }
   
}

No comments:

Post a Comment