I'm doing input validation on a program using JOptionPane boxes. I'm trying to have the input box repeat after the error message every time the user enters in a non-double. How would I do this?
try {
lengthResult = Double.parseDouble(JOptionPane.showInputDialog("What is the length of your garage in square feet?"));
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please enter a number in digit format.","Inane error",JOptionPane.ERROR_MESSAGE);
}
If you want to repeat the message box until the user enters something valid, I'd go like this:
Double lengthResult = null; //Init to null, which is invalid
String title = "Please anter a number";
int initialType = JOptionPane.QUESTION_MESSAGE;
do {
try {
lengthResult = Double.parseDouble(
JOptionPane.showInputDialog(null,
"What is the length of your garage in square feet?",
title, initialType));
} catch (NumberFormatException e) {
initialType = JOptionPane.ERROR_MESSAGE;
title = "Error: Please enter a number!";
}
} while(lengthResult == null); //Iterate as long as no valid input found
Note that this check relies on lengthResult being an Object of type Double, not a primitive type double. With primitive double you'd need some extra flag as you cannot check on lengthResult value this way.
Related
I'm making a cash register with an "other" option, which allows the user to add an amount through user input. I have done this with a JOptionPane, the "other" button code is the following:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt) {
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try {
double overigePrijs = Double.parseDouble(prijs);
if (overigePrijs > 0){
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
}
catch (Exception letter){
while (true){
prijs = JOptionPane.showInputDialog(this, "Vul a.u.b. alleen cijfers in.");
}
}
This while-loop will not close the JOptionPane, even when inputting numbers, how do I loop this correctly?
Edit after almost finishing my SE studies:
I was missing an if-statement in my while-loop. What I was trying to do was checking if the input of prijs were only numbers and if not, keep showing the dialog. I never got around to fixing this because it's an old project but I should have stated the motivation behind the code more clearly!
The question is not clear itself. What I assume that if the try part does not run as you wish, the JOptionPane should reopen and user should be prompted to do it again. If it is so, you can do the following:
Create a method:
private void doTheTask(){
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try{
//your task here.
}
catch (Exception letter){
//Call the method again.
doTheTask();
}
}
And call the method inside your action:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt){
doTheTask();
}
I suggest you a different approach in your code:
String prijs = "";
double overigePrijs = -1;
while (true) {
prijs = JOptionPane.showInputDialog(null, "Vul een bedrag in");
if (prijs != null) { // if user cancel the return will be null
try {
overigePrijs = Double.parseDouble(prijs);
break; // Exits the loop because you have a valid number
} catch (NumberFormatException ex) {
// Do nothing
}
} else {
// You can cancel here
}
// You can send a message to the user here about the invalid input
}
if (overigePrijs > 0) {
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
This code will loop until the user enters a valid number and then you can use after the while loop. Some improvement may be necessary like a cancel logic or change the message on the second time but the main idea is this.
I am having a hard time how to return into specific variable or how to return without getting any error base on my program.
class Facebook {
public static void main(String[]args){
String user = JOptionPane.showInputDialog(null,"Enter Username: ");
String pass = JOptionPane.showInputDialog(null,"Enter Password: ");
if(user.equals("jas")&&(pass.equals("bsit"))){
JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();
Selection.Selection1();
}
else if (!user.equals("jas")||(!pass.equals("bsit"))) {
JOptionPane.showMessageDialog(null,
"Invalid Username or Password",
"Wrong Authentication",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
class Selection{
public Selection1(){
try{
String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);
if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
}
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");
}
else if (numbers == 3){
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);
}
}
}
1) you want a method with a return value of a string
Replace
public Selection1(){
with
public String select()
2) all "paths" of a non-void method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something within the method.
Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...
3) I'm assuming you actually want that value that's returned?
Selection selector = new Selection();
String selected = selector.select();
// TODO use that value
Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.
Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.
I make a little GUI sum program.Program works fine on empty text fields but the problem is when user enter any strings in the text fields the error occur
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "a34dsfsdf"
How to fix error for string types or any characters except numbers
This my Code
private JTextField textfield1;
private JTextField textfield3;
private JTextField textfield4;
private JButton button1;
public ChildClass(){
super("Frame");
button1 = new JButton();
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double number1,baseE,sum;
String text1=textfield1.getText();
String text3=textfield4.getText();
if(text1.isEmpty() && text3.isEmpty()){
JOptionPane.showMessageDialog(null, "Enter Values In TextField", "Invalid TextFields", JOptionPane.ERROR_MESSAGE);
return;
}
else if(!text3.isEmpty() && !text1.isEmpty()){
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
result =number1+basE;
textfield3.setText(""+result);
}
}
});
The error is because you're trying to parse a string as a double.
These two calls:
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
If you look at the documentation:
The parseDouble can throw two exceptions:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable double.
You should put those calls in a try catch block and catch the exception and prompt the user with the error saying they need to enter a valid number.
Something like this should work:
try{
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
result =number1+basE;
textfield3.setText(""+result);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Enter Valid Numbers In TextField", "Invalid TextFields", JOptionPane.ERROR_MESSAGE);
}
I suggest, that you catch the exception in a try catch block.
double number1,baseE,sum;
String text1=textfield1.getText();
String text3=textfield4.getText();
try
{
number1=Double.parseDouble(text1);
baseE=Double.parseDouble(text3);
result=number1+basE;
textfield3.setText(""+result);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Enter Values In TextField", "Invalid TextFields", JOptionPane.ERROR_MESSAGE);
return;
}
Then you can also avoid testing for empty text fields. Empty String throw also an exception.
I have a small issue with my updateButtonResults button. I have JOptionPane Message Dialogs that are programmed to pop up when the user updates the four fields First Name, Last Name, E-mail and Sign-up date. My problem is all 4 messages pop up, even if I only update one field. Example: I update a customers last name, the message dialogs will pop up in this order (First name, Last name, E-mail, Sign-up date).
Here is my code
//method for buttons on 'resultFrame'
public void BtnAction3()
{
updateButtonResults.addActionListener(
new ActionListener()
{
//method for events that will be performed when updateButton is pressed
public void actionPerformed(ActionEvent e)
{
//instanciates variables to text in textfields
String fname = fNameTextBoxResults.getText();
String lname = lNameTextBoxResults.getText();
String email = eMailTextBoxResults.getText();
String signUpDate = signUpTextBoxResults.getText();
try
{
//statement that checks to make sure user enters only letters
if(fname.matches("[a-zA-Z]+"))
{
//updates 'Fname' field in db to text that user inputted in 'fname' textfield
rs2.updateString("Fname", fname);
JOptionPane.showMessageDialog(null, "Customer first name been updated!");
}
//statement that prompts user if they enter something other letters
else
{
JOptionPane.showMessageDialog(null, "Please enter first name in correct format!");
fNameTextBoxResults.setText("");
}
//statement that checks to make sure user enters only letters
if(lname.matches("[a-zA-Z]+"))
{
//updates 'Lname' field in db to text that user inputted in 'lname' textfield
rs2.updateString("Lname", lname);
JOptionPane.showMessageDialog(null, "Customer last name been updated!");
}
//statement that prompts user if they enter something other letters
else
{
JOptionPane.showMessageDialog(null, "Please enter last name in correct format!");
lNameTextBoxResults.setText("");
}
//statement and actions if user enters a '.'
if(email.contains("."))
{
//gets last period in "email"
int emailDotCheck = email.lastIndexOf(".");
//substring to period in variable "emailDotCheck"
String extensionCheck = email.substring(emailDotCheck);
//statement and actions if user doesn't enter email correctly
if(!email.contains("#") || !extensionCheck.matches("\\.[a-z]{3}"))
{
JOptionPane.showMessageDialog(null, "Please enter email in correct format!");
eMailTextBoxResults.setText("");
}
//statement and actions if user enters email correctly
else
{
//updates 'E-mail' field in db to text that user inputted in 'email' textfield
rs2.updateString("E_mail", email);
JOptionPane.showMessageDialog(null, "Customer E-mail been updated!");
}
}
//action if user doesnt enter email correctly
else
{
JOptionPane.showMessageDialog(null, "Please enter email in correct format!");
eMailTextBoxResults.setText("");
}
//instance variables for 'signUpDate'
int month = 100;
int day = 100;
int year = 10000;
if(signUpDate.matches("\\d{2}/\\d{2}/\\d{4}"))
{
//instance variables
String monthStr = signUpDate.substring(0,2);
String dayStr = signUpDate.substring(3,5);
String yearStr = signUpDate.substring(6);
//parsing intstance variables to Integers
month = Integer.parseInt(monthStr);
day = Integer.parseInt(dayStr);
year = Integer.parseInt(yearStr);
//statement and actions if user doesn't follow correct format
if(month > 12 || day > 31 || year > 2100)
{
JOptionPane.showMessageDialog(null, "Please enter date in correct format! (dd/MM/yyyy)");
signUpTextBoxResults.setText("");
}
//statements and actions if user enters date correctly
else
{
//updates 'Sign-up date' field in db to text that user inputted in 'signUpDate' textfield
rs2.updateString("Sign_up_date", signUpDate);
JOptionPane.showMessageDialog(null, "Customer Sign-up date been updated!");
}
}
//statement and actions if user doesn't follow correct format
else
{
JOptionPane.showMessageDialog(null, "Please enter date in correct format! (dd/MM/yyyy)");
signUpTextBoxResults.setText("");
}
//updates row in db
rs2.updateRow();
//JOptionPane.showMessageDialog(null, "Customer has been updated!");
}
catch(Exception ex)
{
}
}
});
I'm trying to learn to walk through my code, I have debugged it, but still couldn't figure the logic error out.
Thanks for any help
You have four text fields:
fNameTextBoxResults
lNameTextBoxResults
eMailTextBoxResults
signUpTextBoxResults
Rather than attempting to validate all of the input at once, let's try to make this code a little more modular. Separate all of the logic pertaining to a specific field and add it as an ActionListener to that field. Example:
fNameTextBoxResults.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//statement that checks to make sure user enters only letters
if(fname.matches("[a-zA-Z]+"))
{
//updates 'Fname' field in db to text that user inputted in 'fname' textfield
rs2.updateString("Fname", fname);
JOptionPane.showMessageDialog(null, "Customer first name been updated!");
}
//statement that prompts user if they enter something other letters
else
{
JOptionPane.showMessageDialog(null, "Please enter first name in correct format!");
fNameTextBoxResults.setText("");
}
}
});
Rinse and repeat for the other three fields. If you have some finalizing type of action required, then you can do that with updateButtonResults. Otherwise, the button is unnecessary altogether.
Instead of using an anonymous class that extends ActionListener, you might want to define a named class that extends it, and defines a constructor by which you could pass in data such as the previous values of the text fields:
class MyActionListener extends ActionListener { // lousy name, but ...
public MyActionListener(String prevFirstName, String prevLastName, String prevEMail, String prevSignUp) {
this.prevFirstName = prevFirstName; ... and so on
}
public void ActionPerformed(ActionEvent e) {
... what you already have, except that you can say things like
if (!fname.equals(prevFirstName)) {
... now you can do your dialog and it won't show up unless the names
... are different
}
...
}
}
and then set it like this:
public void BtnAction3()
{
updateButtonResults.addActionListener(
new MyActionListener(firstName, lastName, eMail, signUp));
}