|
-
Mar 6th, 2008, 10:59 AM
#1
Thread Starter
Lively Member
[RESOLVED] Try / Catch question
In my program I have multiple readLines for the user to enter in numbers, how would I do a try / catch to catch if they enter something other than a number? Could I just use one throw statement for all of them? Any help appreciated, thanks.
Code:
System.out.println("Enter Inventory Number : ");
inventoryNumber = Integer.parseInt(reader.readLine());
-
Mar 6th, 2008, 11:49 AM
#2
Fanatic Member
Re: Try / Catch question
If I get what you want
vb Code:
try { System.out.println("Enter Inventory Number : "); int inventoryNumber = Integer.parseInt(reader.readLine()); } catch (Exception ex){ System.out.println("Enter a Number"); }
-
Mar 6th, 2008, 10:00 PM
#3
Re: Try / Catch question
Since you're using Integer.parseInt I assume you're trying to read an integer number. killer7k's code works fine but why wait for the JVM to throw the exception, which is always a bad idea you can do it in one of 2 ways:
Code:
Scanner s = new Scanner(System.in);
inventoryNumber = s.nextInt();
Or
Code:
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
if (userInput.matches("\\d+")) {
inventoryNumber = Integer.parseInt(userInput);
} else {
System.err.println("Please enter an integer number");
}
The first way is better, the second is only for using the nextLine method.
Oh and BTW use the Scanner class to read user input, it's easier to use and much safer
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|