Check out this little class
Code:
import java.io.*;
import java.text.*;
public class UserInput {
static DecimalFormat df=new DecimalFormat("0.000");
// treat System.in like a buffered reader
static BufferedReader cons=
new BufferedReader(new InputStreamReader(System.in));
public UserInput() {}
/**
* Get an integer from the console
* The Integer.MIN_VALUE is returned on blank input
*/
public int getUserInt(String prompt) {
String inLine=null;
while (true) { // keep on until value ok
System.out.println(prompt+" (blank to stop)");
try {
inLine=cons.readLine().trim();
if (inLine.length()==0) {
System.out.println("Bye for now");
return Integer.MIN_VALUE;
}
return Integer.parseInt(inLine);
}
catch (IOException ex) {
System.err.println("An error occurred");
ex.printStackTrace();
}
catch (NumberFormatException ex) {
System.err.println(inLine+" is not an integer");
}
System.err.println("Please reenter");
}
}
/**
* Get a double from the console
* The Double.MIN_VALUE is returned on blank input
*/
public double getUserDouble(String prompt) {
String inLine=null;
while (true) { // keep on until value ok
System.out.println(prompt+" (blank to stop)");
try {
inLine=cons.readLine().trim();
if (inLine.length()==0) {
System.out.println("Bye for now");
return Double.MIN_VALUE;
}
return Double.parseDouble(inLine);
}
catch (IOException ex) {
System.err.println("An error occurred");
ex.printStackTrace();
}
catch (NumberFormatException ex) {
System.err.println(inLine+" is not a valid decimal number");
}
System.err.println("Please reenter");
}
}
/**
* Get a string from the console
*/
public String getUserString(String prompt) {
System.out.println(prompt+" (blank to stop)");
while (true) { // keep on until input ok
try {
return cons.readLine().trim();
}
catch (IOException ex) {
System.err.println("An error occurred");
ex.printStackTrace();
}
}
}
/***********************
* Main (for test)
*/
public static void main (String [] args) {
UserInput ui=new UserInput();
int n=ui.getUserInt("Enter a whole number");
if (n==Integer.MIN_VALUE) System.exit(0);
System.out.println("You entered: "+n);
double d=ui.getUserDouble("Enter a decimal number");
if (d==Double.MIN_VALUE) System.exit(0);
System.out.println("You entered: "+df.format(d));
String s=ui.getUserString("Enter some text");
if (s.length() > 0) {
System.out.println("You entered: " + s);
}
System.out.println("Bye for now");
}
}
Bookmarks