Results 1 to 6 of 6
- 10-30-2010, 04:49 AM #1
Member
- Join Date
- Oct 2010
- Posts
- 4
- Rep Power
- 0
Preventing errors when typing a letter into a String
I would like general guidance on how to avoid an error when someone tries to type a letter into an integer from the scanner class. My program asks for a number, but if someone types a letter in it gives multiple errors and I would like to know how to avoid this.
I think I would use a try, catch, but I am not exactly sure how to implement that. What error do I put in the catch? Can I just use one statement for all errors?
I was thinking something like this
try{
x = scanner.nextInt}
catch(Exception x){
}
What do I put in the spot where I have exception?Last edited by doymand; 10-30-2010 at 04:52 AM.
- 10-30-2010, 05:28 AM #2
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 12
- 10-30-2010, 06:54 AM #3
You could try something like:
Java Code:String example = "12a"; try { int temp = Integer.parseInt(example); } catch(NumberFormatException e) { System.out.print(e); }
In short, it tries to convert your string to an integer number. If it can't then it will throw an error meaning your string is not a number.Sincerely, Joshua Green
Please REP if I help :)
- 10-30-2010, 10:23 AM #4
Member
- Join Date
- Oct 2010
- Location
- Fort Wayne, IN
- Posts
- 7
- Rep Power
- 0
Here is what you need:
Scanner scan = new Scanner(System.in);
int number = 0;
System.out.print("Enter a number: ");
try
{
number = scan.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("A Non-numeric data was entered");
System.exit(0);
}
System.out.println(number);
- 10-30-2010, 11:44 AM #5
Honopac, at least let them try to figure it out...
Sincerely, Joshua Green
Please REP if I help :)
- 10-30-2010, 07:56 PM #6
Member
- Join Date
- Oct 2010
- Location
- Fort Wayne, IN
- Posts
- 7
- Rep Power
- 0
Similar Threads
-
Preventing local copies of fields
By Steve11235 in forum Threads and SynchronizationReplies: 2Last Post: 08-05-2009, 06:51 AM -
String is not accepting "*" letter, please help me to solve
By srisar in forum New To JavaReplies: 18Last Post: 07-12-2009, 06:47 PM -
preventing access/locking a folder?
By solris in forum New To JavaReplies: 1Last Post: 06-29-2009, 01:20 AM -
the number of occurrences of each alphabetical letter in the string.
By masaka in forum New To JavaReplies: 20Last Post: 05-14-2008, 10:42 AM -
Preventing inserted text from becoming colored from previous style
By jkhoa in forum AWT / SwingReplies: 2Last Post: 08-10-2007, 01:36 AM
Bookmarks