Results 1 to 2 of 2
  1. #1
    Camden is offline Member
    Join Date
    Nov 2007
    Posts
    13
    Rep Power
    0

    Default 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

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    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

  1. How to handle socket Exception
    By mayank0512 in forum Networking
    Replies: 14
    Last Post: 12-21-2010, 11:31 PM
  2. [SOLVED] Handle own exception
    By stevemcc in forum New To Java
    Replies: 3
    Last Post: 04-10-2008, 04:55 AM
  3. Better way to handle exceptions
    By javaplus in forum Advanced Java
    Replies: 2
    Last Post: 01-16-2008, 06:47 PM
  4. how to handle exceptions
    By paty in forum Advanced Java
    Replies: 2
    Last Post: 08-05-2007, 04:17 AM
  5. how to take input and verify input in Java programs
    By bilal_ali_java in forum Advanced Java
    Replies: 0
    Last Post: 07-21-2007, 08:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •