Java JDK 1.5+ Better Way To Read User Input


You Java programmers out there may think I’m crazy but I haven’t written anything in Java for at least 4 years, and in that time the talented guys over at Sun Microsystems have made reading user input much much easier than the old days of JDK 1.4 where we had to suffer with using bufferedinputstream objects.

For those of you who may be new to Java or are coming back to it (like me) after a long hiatus you will be very happy to know there is a nice handy class you can call upon to do this for you…the Scanner Class.

The scanner class is much easier to use to capture user input these days. All you do is create the object:

Scanner in = new Scanner(System.in);

Then call the appropriate method to capture a string, integer, long, etc.

number = (double)in.nextInt();

Here’s a quick example of it in action:

import java.io.*;
import java.util.Scanner;
public class MyUserInput
{
  public static void main(String[] args)
  {
    double number;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter your gross income: ");
    if (in.hasNextInt())
    {
      number = (double)in.nextInt();
      System.out.println("You entered " + number);
    }
    else if (in.hasNextFloat())
    {
      number = (double)in.nextFloat();
      System.out.println("You entered " + number);
    }
    else if (in.hasNextDouble())
    {
      number = in.nextDouble();
      System.out.println("You entered " + number);
    }            
    else
      System.out.println("Token not an integer or a real value.");  
  }
}

A much easier alternative to what we used to have to go through. Many of you may have written your own classes when JDK 1.4 was used to simplify the process (which was what I did) but this new way is a real nice way to capture input.

Advertisements

One thought on “Java JDK 1.5+ Better Way To Read User Input

  1. i love programming in java am a learner and the problem of using “Textio.getin()” function to capture user input. pliz help me out. thanx. reply via email……………

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s