ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Using Try/Catch Blocks with Java Dialogues

Updated on April 14, 2013
Source

Using Type Casting and the TRY/CATCH Block with Java Swing Dialogues

One of the most important things to remember when you decide to create a user interface is to expect possible user errors that may come up. Indeed, one of the most embarrassing things that could happen in your program is when you ask for user input and they accidentally enter the wrong input type and your program crashes. Yes, it is true that the user made the error, however, as a programmer you must keep this in mind when trying to create you interface.

So, what can you do to make sure this never happens? Well, like all programs, there must be prior planning before you decide that the program is good and try to export it as a usable product. You must consider not only what the interface must look like but how it will handle possible errors. Of course the possibilities are great, however, if you plan out your program prior to writing any code or module, you can possibly catch most of these input errors before you program ever makes it to the market.

In this article, I will create code using dialogues in Java’s Swing class to show you how you can use a generic try/catch block that will allow you to catch a type of input error in which you can correct while the program is running. First, I will show you what I usually do to plan out the specifics of a program by showing you how to use a flow chart and pseudo code. Secondly, this program will also show you how to type cast string input from a Java based dialogue box and change the input to a number in which you can manipulate the number via any type of math algorithm. Third, I will show you how to use a try/catch block to catch user input errors. Last, I will show you the actual JAVA code that I created in NetBeans using the built in JAVA Swing class. Again, as stated earlier, the version of NetBeans I will be using is 7.0.1.

Planning for Possible Errors:

One of the things I like to do is to find out what exactly the user needs from a particular interface. Is it to add numbers or enter text? You have to remember that in pretty much all programming languages there is something known as variable type. When you define a variable or class it is a type (i.e. an int, double, String, etc.). This type must be exact and the only way to make sure user input is the same type is to either catch the error before it is processed or purposely cast the type to fit the correct input.

So, you may have to plan how you will handle this issue by planning accordingly. When I create a plan to handle such issues of a programming language, I usually will fill out a flowchart with some pseudo code (i.e. code that represents more of an English view without actually using a programs code.). In the case of this example, I want to ask the user to input two numbers by way of two dialogue boxes and in return the program will add the two numbers and show a dialogue box with the results. With that said, the following would be the flowchart and pseudo code I would use to help me plan to create the program that catches any incorrect user inputs.

Program FLow Chart

So, by looking at this flowchart, I can plan out the code to catch input errors made by the user and have the program request the correct input. Now the following would be the pseudo code I would use in this situation. Remember, pseudo code is not program specific, it just give you a visual or idea on how you may write the code later within the programming language that you choose.

Program Pseudo-Code

boolean done = false;

While (!done)

String firstNumber = Show Dialogue (input firstNumber);

String secondNumber=Show Dialogue (input seconeNumber);

Try {

Double number1 = cast (firstNumber);

Double number 2 = cast (firstNumber);

Double sum = number1 + number 2;

showMessageDialogue (sum);

done = true;

}

Catch (numberException)

{

showDialogue (“You have to Enter Two Numbers”)

}

Again, the above is only a pseudo code and could be refined to any programming language you wish. Just remember that pseudo code is only a tool to give you an idea how you want the program to flow.

As you can see above, I created a plan that would ask the user to input two numbers via two different dialogue boxes. The try/catch block then takes in the input and determines if the input is correct. If the input is correct, then the two numbers are summed up and the while loop is ended since the Boolean variable “done,” is now set to true. However, if the input where not numbers, the catch block would catch it and produce an error that would ask the user to reenter the number. If it wasn’t for this try/catch block, the program would crash and the user may never know the reason why.

With that said, the following is the code that I ended up with using Java. I am presently using the NetBeans version 7.0.1:

//**********************************************************
//
// Author: Bink
//
// Description: Ask the user to input numbers into 
//              two dialogues and then add the numbers for input 
//              to a third java dialogue.
//              If input is not a number, show the error to the user
//
//***************************************************************
package addtiondialogues;
 
//This program uses JOptionPane
import javax.swing.JOptionPane;
 
public class AddtionDialogues {
 
    public static void main(String[] args) {
         
       boolean done = false;//Control Variable for the while loop
        
       //repeat until a valid input is entered
       while(!done)
       {
           //Obtain user input using two JOption Pane dialogues
           String firstNumber = JOptionPane.showInputDialog("Enter first integer");
           if(firstNumber == null || firstNumber.length() == 0) {
               firstNumber = "0";
            }
           String secondNumber = JOptionPane.showInputDialog("Enter second integer");
           if(secondNumber == null || secondNumber.length() == 0) {
               secondNumber = "0";
            }

         
            //convert String input to int values to use in a calculation
            //Catch an error if input was not a number
            try{
            double number1 = Double.parseDouble(firstNumber);//change to double
            double number2 = Double.parseDouble(secondNumber);//change to double
             
            //Add input values (number1 + number2) to sum variable
            double sum = number1 + number2;
             
            //Show results in a new JOptionPane dialogue
            JOptionPane.showMessageDialog(null, "The sum is " + sum,
                    "Sum of Two Integers",JOptionPane.PLAIN_MESSAGE);
            //exit while loop
            done = true;
            } //Catch error if input was not a number and repeat while loop.
            catch ( NumberFormatException e){
                JOptionPane.showMessageDialog(null, 
                        "Error: You have to enter two numbers!",
                        "Error Message",JOptionPane.ERROR_MESSAGE);
                }//end try/catch block       
       }//end while loop
    }//end main
}//end AdditionDialogues Class

So, now I will explain the code above to give you an idea what is going on. First, I created a new project with the package name of “additional dialogues,” with a public class name of “Additional Dialogues.” I also imported the built Java class “javax.swing.JOptionPlane.” This imported class will allow you create dialogues for input.

Within the Additional Dialogue class you have the main function. This function is the entry point to your program. Next I set up a Boolean variable “done,” which will be the variable that controls your while loop. If the user enters the numbers correctly, then this Boolean variable will change to true and the loop will be exited.

Next, we have the while loop. As stated above, the wile loop will continuously run until the correct input is entered. Since the variable “done,” is set to false, then the symbol “!” is used to tell the while loop that until this variable is true, continue looping.

The next variables will hold the input string that the user enters and will initialize two individual dialogue boxes to get that input. When you use dialogue boxes, the input that the user enters will be of a string value. This also goes for numbers as well.

The next section of code is the try/catch block. This is where the decision is made to determine if the user did indeed actually enter integers and not other type of characters. Within the try block I created two new double type variables (double type variables allow you to use decimal variables). These two variables will be use to add the two numbers inputted by the user. You may also noticed that both variables use a parsing statement (i.e. number1 = Double.parseDouble (firstNumber)). This is called type casting. Remember that the type that the user inputs within the dialogue box is a string; however, you cannot use any type of math algorithm with strings, only numbers. So, user input has to be what programmers call “type casted,” to make sure that any math on inputted numbers can be done. Finally, within this block, the numbers are added and returned to the user via a dialogue box and the loop variable of done is set to true to end the loop.

However, if within the try block, the input from the user was not a number, then the catch block is ran and the user is asked to enter the correct input. So, the program will continue to run until the user finally inputs the correct information. With that said, the following graphics shows and example of what happens when you finally run this program:

Figure 1: User enters random character

Figure 2: User enters a letter as input.

Figure 3: Program produces an error and user is asked to re-input intergers

Figure 4: User re-inputs first integer.

Figure 5: User inputs second integer.

Figure 6: Program returns correct result to user.

Final Conclusion

In this example, I showed you how to create a simple version of a graphic user interface in which the user can enter input. I also showed how to use type casting in java as well as how to use a try/catch block to catch any errors and in turn to keep the program from crashing. However, this program is still not crash proof. There is one problem with this program that I did not cover as it pertains to user input. I decided to leave it up to you to decide what that problem is. However, I will give you a hint: The cancel button on the dialogue buttons could cause your program to crash. Again, I will leave it up to you to figure out how to compensate for this problem and figure out how to change the program to catch this error. Happy coding!!!!

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)