Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / January 2007

Tip: Looking for answers? Try searching our database.

Data Validation

Thread view: 
BlackJackal - 29 Jan 2007 22:44 GMT
I am really new to programming so take it easy on  me :)

Here is the code.  Basically what I want it to do is whenever the user
enters in 1 2 or 3 to say good job.  When the user enters 4 to quit
and anything else display an error message.  This code works fine as
long as the user enters in a int if anything else is entered it
crashes.  How can i fix this?  Thanks

  import javax.swing.*;
   public  class Input123
  {
      public static void main(String[] args)
     {
        String input;
        int selection = 0;
        while (selection != 4) {
           input = JOptionPane.showInputDialog(null,"Enter in either
1, 2, 3, or 4 to quit");
           selection = Integer.parseInt(input);
           if(selection == 1 || selection == 2 || selection == 3) {
              JOptionPane.showMessageDialog(null,"Good Job");
           }
           else if(selection == 4){
              System.exit(0);
           }
           else  {
              JOptionPane.showMessageDialog(null,"You have entered an
invalid character, Please try again.");
           }

        }

        System.exit(0);
     }
  }
Eric Sosman - 29 Jan 2007 23:01 GMT
BlackJackal wrote On 01/29/07 17:44,:
> I am really new to programming so take it easy on  me :)
>
[quoted text clipped - 31 lines]
>       }
>    }

   If the user enters junk, Integer.parseInt() will throw
NumberFormatException.  If you want to keep going after the
exception is thrown, you must catch it and deal with it.
Here's one way:

    while (true) { // selection != 4 is useless
       input = ...;
       try {
           selection = Integer.parseInt(input);
       }
       catch (NumberFormatException ex) {
           selection = 0;
       }
       if (... as above ...)
    }

Signature

Eric.Sosman@sun.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.