Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: int / double validation

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Location
    Jackson, MI
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default int / double validation

    I have 95% of my code written but cannot figure out how to set up the error checking for when the user enters letters in a field that requires numbers.

    Assignment : Create an interactive gui program that converts miles to kilometers and vice versa, dependent on what the user chooses. Also requires error checking for input other than integers or doubles.

    Here is my code thus far.
    [highlight = java]
    import javax.swing.JOptionPane;
     
    public class Converter
     
    {
     
     
     
     
    	public static void main(String args[])
    	{
    		String converterChoice;
     
    		int i = 0;
    		// counter for loop
    		while (i < 1)
    		// loop continues until the user enters valid information
    		{
     
    			converterChoice = JOptionPane.showInputDialog("Would you like to convert English or Metric distance: ");
    	 		if (converterChoice.equals("Metric"))
    				 metricCoverter();
    			else if (converterChoice.equals("English"))
    				englishConverter();
    			else JOptionPane.showMessageDialog(null, "Your Entry is invalid, please retry", "Error", JOptionPane.INFORMATION_MESSAGE);
    		}
    	}
    	public static void metricCoverter()
    	{
    		String metricEntry;
    		double metricDouble;
    		double conversion;
     
    		metricEntry = JOptionPane.showInputDialog("Enter the number of kilometers to be converted to miles: ");
    		//create a double from the string
    		metricDouble = Double.parseDouble(metricEntry);
    		//convert to kilometers
    		conversion = metricDouble * .62;
    		JOptionPane.showMessageDialog(null, "Your entry of " + metricEntry + "miles converts to " + conversion + "kilomters", "Conversion to Kilometers", JOptionPane.INFORMATION_MESSAGE);
    	}
    	public static void englishConverter()
    	{
    		String englishEntry;
    		double englishDouble;
    		double conversion;
     
    		englishEntry = JOptionPane.showInputDialog("Enter the number of miles to be converted to kilometers: ");
    		//create a double from the string
    		englishDouble = Double.parseDouble(englishEntry);
    		//convert to miles
    		conversion = englishDouble * 1.609344;
    		JOptionPane.showMessageDialog(null, "Your entry of " + englishEntry + "kilometers converts to " + conversion + "miles", "Conversion to Miles", JOptionPane.INFORMATION_MESSAGE);
    	}
    }
    [/highlight]
    Can anyone give me a hint on this one?
    Thanks
    Last edited by exnuke1972; January 19th, 2011 at 04:18 PM.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: int / double validation

    When posting code, make sure you use the code tags. Nobody likes to read unformatted code.

    There are a few different way to do this. You could read the values in as Strings, then make sure each character is a digit before converting (see the API for String and Character for useful functions), or you could catch the Exception thrown when you try to convert a non-numeric String into a number.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: int / double validation

    try/catch statements. I'm sort of in the middle of something, so I can't really go too indepth. Basically, before you read in the number the user inputs, put a try statement. At the end of whatever segment of code you are working with, add a catch(Exception ex){...} statement. Then assume the user will input a number. If there is a problem with converting the user's input into a number, an exception will be thrown which is caught by the catch statement, where you have specified what to do in the event of an exception being thrown.

    I'll post some code later if no one beats me to it.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: int / double validation

    int i =0;
     
    while (i < 1)
    		// loop continues until the user enters valid information
    		{
     
    			converterChoice = JOptionPane.showInputDialog("Would you like to convert English or Metric distance: ");
    	 		if (converterChoice.equals("Metric"))
    				 metricCoverter();
    			else if (converterChoice.equals("English"))
    				englishConverter();
    			else JOptionPane.showMessageDialog(null, "Your Entry is invalid, please retry", "Error", JOptionPane.INFORMATION_MESSAGE);
    		}

    That's an infinite loop.

    Also, for English or Metric, are you allowed to have buttons instead?
    JFrame frame = new JFrame();
     
    Object[] options = {"English", "Metric"};
                        int n = JOptionPane.showOptionDialog(frame,
                                        "Message",
                                        "Title",
                                        JOptionPane.YES_NO_OPTION,
                                        JOptionPane.QUESTION_MESSAGE,
                                        null,
                                        options,
                                        options[0]);
    if (n == JOptionPane.YES_OPTION)
    {
     
    // stuff for English system
     
    }
     
    else if (n== JOptionPane.NO_OPTION)
    {
    // Metric System
    }
     
    else if (n== JOptionPane.CLOSED_OPTION)
    {
    // exit or do something if they just exit the dialog
    }
     
    else
    {
    System.out.println("Error");
    }

    Also, for the error checking, have a while loop that has a boolean set to false and will continue while boolean is false.

    Define value you're using before while loop and catch block. Or at least initialize them.

    Then have a try block that has the user enter the stuff in a JOptionPane.

    At the end, before the ending bracket of try block, set boolean to true.

    Then create a catch block
    catch(NumberFormatException nfeRef)
    {
    // what to pop up if value is wrong type
    valueEntered = 0; // I think it has to reset value again so it won't go on forever, could be mistaken.  
    }
    If there is an error, it'll go to the catch block , if not, it'll set condition to true and end while loop.
    Last edited by javapenguin; January 20th, 2011 at 05:09 PM.

  5. #5
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: int / double validation

    Maybe I'm wrong about some things, but I did find a site that might explain how to do it
    Java Exception Handling: Basic Try Catch Finally

Similar Threads

  1. Jtextfield Validation
    By nimishalex in forum AWT / Java Swing
    Replies: 8
    Last Post: December 11th, 2010, 02:42 AM
  2. Exception during xml validation
    By vijeta in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 6th, 2010, 02:50 AM
  3. IPv6 validation
    By subhvi in forum Java Networking
    Replies: 1
    Last Post: November 27th, 2009, 07:19 AM
  4. Input Validation
    By nic in forum AWT / Java Swing
    Replies: 4
    Last Post: November 18th, 2009, 10:54 AM
  5. Problems with If validation
    By websey in forum Loops & Control Statements
    Replies: 1
    Last Post: November 18th, 2009, 09:43 AM