![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Dec 2005
Posts: 40
Rep Power: 0
![]() |
Little Error checking help
I've got two methods which take in information from the user. One which takes in Strings:
public static String getNames(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = null;
try{
name = br.readLine();
} catch (IOException ioe){
System.out.println("Error trying to read input");
System.exit(1);
}
return name;
}and one which takes in Integers: public int getNums()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
int num = 0;
try{
input = br.readLine();
num = Integer.parseInt( input );
} catch (IOException ioe){
System.out.println("Error trying to read input");
System.exit(1);
}
return num;
}The problem is that if the user enters a string when the system expects an integer, there is an error and the system crashes. Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "r" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) Any idea on what to write to ensure the user enters an integer when asked? |
|
|
|
|
|
#2 | |
|
Professional Programmer
Join Date: May 2006
Location: UK - London
Posts: 329
Rep Power: 3
![]() |
"Please enter a number from [min] to [max]....if you don't enter a number this program will crash"
![]()
__________________
Quote:
|
|
|
|
|
|
|
#3 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
While that seems like a joke, there is a large measure of truth involved. YOU DO NOT HAVE CONTROL OF YOUR USER. Instead, you use a function that tells you whether or not the user complied with your requirements. Then you check what the function had to say. If your function doesn't have that ability, the function was written by a schlock. If your function has that ability, but you don't use it, you are either uninformed, or a schlock.
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#4 |
|
Sexy Programmer
|
Just have another catch statement to catch the NumberFormatException!
public int getNums()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
int num = 0;
try
{
input = br.readLine();
num = Integer.parseInt( input );
}
catch (IOException ioe)
{
System.out.println("Error trying to read input");
System.exit(1);
}
catch(NumberFormatException nfe)
{
System.out.println("enter an integer value!!");
System.out(1);
}
return num;
}
__________________
I would love to change the world, but they won't give me the source code! |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|