Sample code for taking user input from Shell

aj.wh.ca 0 Tallied Votes 237 Views Share

Sample code for taking input from Shell demonstrating string and int input
For simple programs or testing purpose its not always required to take input thru GUI.

/**
 * Sample code for taking input from Shell demonstrating 
 * string and int input
 * For simple programs or testing purpose its not always 
 * required to take input thru GUI.
 *
 * @author  aj.wh.ca
 * #link 	www.swiftthoughts.com
 */

import java.io.*;

public class ShellUtils
{
      //get String or simply enter from shell
      public static String getStringFromShell(String prompt)
      {
            try
            {
                  System.out.print(prompt);
                  return new BufferedReader(new InputStreamReader(System.in)).readLine();		
            }
            catch (IOException e)
            {
                  e.printStackTrace();
            }
            return null ;
      }

      // get an int. Keep asking until not
      public static int getIntFromShell(String prompt)
      {
            String line = "" ;
            int num = 0 ;
            while(line.equals(""))
            {
                  line = getStringFromShell(prompt);
                  try
                  {
                        num = Integer.parseInt(line);
                  }
                  catch(NumberFormatException e)
                  {
                        System.out.println("Error: Invalid number");
                        line = "" ;
                  }
            }
            return num ;
      }

      // similiar methods can be made for getting char , double etc

      public static void main(String args[])
      {
            String name = ShellUtils.getStringFromShell("Please enter your name ");
            int age = ShellUtils.getIntFromShell("Please enter your age ");

            System.out.println(name + " is "+ age + " years old !!!");
      }

}
Suryakiran -2 Newbie Poster

For taking input of an integer use this code

import java.io.*;
class inputno
{
public static void main(String args[]) throws IOException
{
int a;
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
a=Integer.parseInt(br.readLine());
}
}

commented: Original code snipped is better then yours, so worthless input from you -2
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Whenever you do this:

return new BufferedReader(new InputStreamReader(System.in)).readLine();

you keep creating a new BufferedReader every time you call the method.
Not very efficient.
Try and have the BufferedReader as static and then use it form the static methods.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.