Results 1 to 2 of 2
Thread: handle wrong input int/null
- 12-16-2007, 03:39 PM #1
Member
- Join Date
- Nov 2007
- Posts
- 13
- Rep Power
- 0
handle wrong input int/null
Lets say we got a program and we want someone to type either 1 or 2 in order to do something. If they type 1) any other integer or if 2) they do not type anything (and just press enter), how can i make the program not crash? I mean e.g. if they type 4 then the program to show again the phrase 'please type either 1 or 2'; and to repeat again and again the prompt until the user types 1 or 2. thank you
- 12-16-2007, 10:37 PM #2
You can use some if-else statements to test/qualify the iuput.
For example,
Java Code:BufferedReader reader = ... int n = -1; do { System.out.println("enter 1 or 2"); String line = reader.readLine(); if(line != null && line.length() > 0) { // User entered something so we may have something to parse. // You may want to check that "line" contains parsable digits // with something like [i]Character.isDigit[/i]. // Or, you could use a try/catch for NumberFormatException. n = Integer.parseInt(line); } } while(n != 1 && n != 2);
Similar Threads
-
How to handle socket Exception
By mayank0512 in forum NetworkingReplies: 14Last Post: 12-22-2010, 12:31 AM -
[SOLVED] Handle own exception
By stevemcc in forum New To JavaReplies: 3Last Post: 04-10-2008, 05:55 AM -
Better way to handle exceptions
By javaplus in forum Advanced JavaReplies: 2Last Post: 01-16-2008, 07:47 PM -
how to handle exceptions
By paty in forum Advanced JavaReplies: 2Last Post: 08-05-2007, 05:17 AM -
how to take input and verify input in Java programs
By bilal_ali_java in forum Advanced JavaReplies: 0Last Post: 07-21-2007, 09:46 AM
Bookmarks