Monday, March 9, 2009

Reading command Line Input in JAVA

Hi,

Developers migrating from c++ to java are first think of how
to pass command line input to java application or how to read command
line input in JAVA.

I am also worried on my early days of learning java.
So friends here I have some example to do so.

We can use BufferedReader class for that.
--------------------------------------------------------------------------------
import java.io.*;

public class ReadString
{
          public static void main(String[] args)
          {
                   //  prompt the user to enter their name
                   System.out.print("Enter your name: ");

                   //  open up standard input
                   BufferedReader br = new BufferedReader(new                
                                                 InputStreamReader(System.in));
                   String userName = null;

                   //  read the username from the command-line
                   try
                   {
                             userName = br.readLine();
                   }
                   catch (Exception e)
                   {
                             System.out.println(e);
                   }
                   System.out.println("UserName =  " + userName);
          }
}
======================================

Java 5.0 gives a new feature for reading inputs.
They launch java.uti.Scanner class, it gives more flexibility for reading
a input.

You can read from any file or you can search by a particular pattern.

import java.util.Scanner;
public class InputTest
{
          public static void main(String as[])
          {
                   String name = "";
                   int age = 0;

                   Scanner sc = new Scanner(System.in);
                   name = sc.nextLine();
                   age = sc.nextInt();
                   sc.close();
                   System.out.println("Name :-" + name);
                   System.out.println("Age :-" + age);
          }
}
=======================================

No comments:

Post a Comment