Difference between revisions of "Input Validation"

From CompSciWiki
Jump to: navigation, search
Line 30: Line 30:
 
message.equals("a")
 
message.equals("a")
 
</pre>
 
</pre>
For our problem we want to continue to ask until we get a valid letter. While loops keep running while the test condition = true. So we have to negate the returned value so that we get false to exit the loop on valid input. We can use <pre>!</pre> in front of the method call to negate the answer.
+
For our problem we want to continue to ask until we get a valid letter. While loops keep running while the test condition = true. So we have to negate the returned value so that we get false to exit the loop on valid input. We can use "!" in front of the method call to negate the answer.
 
<pre>
 
<pre>
 
boolean result;
 
boolean result;

Revision as of 10:07, 8 April 2010

Back to the Program-A-Day homepage

Problem

Prompt the user for input until they enter either a, b, or c. Use the following guidelines in coming up with a solution:

 

While and For Loops

Wiki loops03.jpg

Solution

To use JOptionPane you will need to include the following import statement.

import javax.swing.JOptionPane; //needed for JOptionPane

We will need one String variable message. For getting input from the JOptionPane input dialog.

String message; //used to store the input from the user.

To get input from the user we use the following line of code.

//gets input from the user
message = JOptionPane.showInputDialog("Please Enter a, b or c:");

To validate our input we are going to need to used the .equals() method. For strings this will compare the contents of two passed strings. The equals method returns true if the two strings matched.

//checks if message is equal to a
//returns true if true
message.equals("a")

For our problem we want to continue to ask until we get a valid letter. While loops keep running while the test condition = true. So we have to negate the returned value so that we get false to exit the loop on valid input. We can use "!" in front of the method call to negate the answer.

boolean result;

//result will now equal false when message = "a"
result = !(message.equals("a"))

Code

Solution Code

Back to the Program-A-Day homepage