Sample code for taking user input from Shell

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
aj.wh.ca aj.wh.ca is offline Offline Mar 29th, 2005, 8:51 pm |
0
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.
Quick reply to this message  
Java Syntax
  1. /**
  2.  * Sample code for taking input from Shell demonstrating
  3.  * string and int input
  4.  * For simple programs or testing purpose its not always
  5.  * required to take input thru GUI.
  6.  *
  7.  * @author aj.wh.ca
  8.  * #link www.swiftthoughts.com
  9.  */
  10.  
  11. import java.io.*;
  12.  
  13. public class ShellUtils
  14. {
  15. //get String or simply enter from shell
  16. public static String getStringFromShell(String prompt)
  17. {
  18. try
  19. {
  20. System.out.print(prompt);
  21. return new BufferedReader(new InputStreamReader(System.in)).readLine();
  22. }
  23. catch (IOException e)
  24. {
  25. e.printStackTrace();
  26. }
  27. return null ;
  28. }
  29.  
  30. // get an int. Keep asking until not
  31. public static int getIntFromShell(String prompt)
  32. {
  33. String line = "" ;
  34. int num = 0 ;
  35. while(line.equals(""))
  36. {
  37. line = getStringFromShell(prompt);
  38. try
  39. {
  40. num = Integer.parseInt(line);
  41. }
  42. catch(NumberFormatException e)
  43. {
  44. System.out.println("Error: Invalid number");
  45. line = "" ;
  46. }
  47. }
  48. return num ;
  49. }
  50.  
  51. // similiar methods can be made for getting char , double etc
  52.  
  53. public static void main(String args[])
  54. {
  55. String name = ShellUtils.getStringFromShell("Please enter your name ");
  56. int age = ShellUtils.getIntFromShell("Please enter your age ");
  57.  
  58. System.out.println(name + " is "+ age + " years old !!!");
  59. }
  60.  
  61. }
  62.  
-1
Suryakiran Suryakiran is offline Offline | 25 Days Ago
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());
}
}
 
0
javaAddict javaAddict is offline Offline | 24 Days Ago
Whenever you do this:
  1. 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.
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC