Tuesday, August 9, 2011

Command Line Input with Java

I learned first programming language(C and C++) using command line input and output; and it was really interesting. Then after I started Java, and because java was high level programming language, I was quite involved creating forms and performing input and output operations using GUI fields which used to be a quite easy way to do. But unfortunately, I did not notice to implement the command line input and output and if you are also not aware or may have forgotten, then here I am going to point out the methods to accomplish this.(Note: there may be many alternatives for that)
We note here that System.in gets the stream from primary input devices such as keyboard.

1) Using Scanner Object

// prompt the user to enter their name
System.out.print("Enter your name: ");

// get their input
Scanner scanner = new Scanner(System.in);

// there are several ways to get the input, this is
// just one approach
String username = scanner.nextLine();
//Display name
System.out.println("Your Name is:"+username);

2) Using BufferedReader Object

// 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));

// read the username from the command-line; need to use try/catch with the
// readLine() method
String userName = br.readLine();

//Display Name
System.out.println("Your Name is:"+userName);

The above mentioned code is quite straightforward and its your choice which method to use.
Thanks for your effort to read my article.

Here are some useful methods we can directly use in applications:
   // to get string
   public static String getString() throws IOException
      InputStreamReader isr = new InputStreamReader(System.in);
      BufferedReader br = new BufferedReader(isr);
      String s = br.readLine();
      return s;

    // to get a character
   public static char getChar() throws IOException
      String s = getString();
      return s.charAt(0);

    //to get integer
   public static int getInt() throws IOException
      String s = getString();
      return Integer.parseInt(s);

No comments:

Post a Comment