如何将 JTextField 输入转换为 int 以进行验证?

How can I convert JTextField input into int for validation?

我需要帮助将文本字段输入转换为 int 以进行验证。 contactnum 来自字段 textFieldContactnum。 我想将 textFieldContactnum 的输入转换为 int。 我试过先将 textFieldContactnum.getText() 存储到一个字符串中,然后使用一个新的 int (contactnumber) 来解析 (Integer.parseInt),就像下面的代码一样……

 private void actionPerformedOk() {
        String username = textFieldUsername.getText();
        String password = passwordField.getText();
        String email = textFieldEmail.getText();
        String securityqn = textFieldSecurityqn.getText();
        String securityanswer = textFieldSecurityanswer.getText();
        contactnumber = textFieldContactnum.getText();
        int contactnum = Integer.parseInt(contactnumber);
        String firstname = textFieldFirstName.getText();
        String lastname = textFieldLastName.getText();
        String gender = genderSelected;
        String nric = textFieldNRIC.getText();
        String address = textFieldAddress.getText();
        postalcode1 = textFieldPostalCode.getText();
        int postalcode = Integer.parseInt(postalcode1);

        String day = dayList.getSelectedItem().toString();
        String month = monthList.getSelectedItem().toString();
        String year = yearList.getSelectedItem().toString();

        if (!day.equals("Day") && !month.equals("Month") && !year.equals("Year")) {
             dateAsString = day + "/" + month + "/" + year;
             SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
             try {
                 Date date = sdf.parse(dateAsString);
                    System.out.println(date);
             } catch (ParseException e1) {}

        }

        dateAsString = day + ("/") + month + ("/") +  year;

        String date = dateAsString;
 // retrieve the user input from the text box/area provided
         if (validateInput()) {
             username = textFieldUsername.getText();

 if (actions.equalsIgnoreCase("Submit")){
signup = new hiroSIGNUP(username, password, email, securityqn, securityanswer, contactnum, firstname, lastname, gender, nric, address, postalcode, date);
 actionPerformedCreate();
 }

 else{ 
 // update the values of the current expense object 
     //update empty to some fields
 signup.setUsername(username);
 signup.setPassword(password);
 signup.setEmail(email);
 signup.setSecurityqn(securityqn);
 signup.setSecurityanswer(securityanswer);
 signup.setContactnum(contactnum);
 signup.setFirstname(firstname);
 signup.setLastname(lastname);
 signup.setGender(gender);
 signup.setNric(nric);
 signup.setAddress(address);
 signup.setPostalcode(postalcode);
 signup.setDate(date);
 actionPerformedUpdate();
 }
         }
 }
 /**
 * Purpose: This method updates the expense record
 * in the database.
 * Input: Nil
 * Return: void
 */

 public void actionPerformedUpdate(){
 // Update record in database and check return value
 if (SignupDA.updatehiroSIGNUP(signup)) {
 JOptionPane.showMessageDialog(myFrame,
 "Record updated successfully", "Alert",
 JOptionPane.INFORMATION_MESSAGE);
 // reset text field for next record.
 textFieldUsername.setEditable(false);
 passwordField.setEditable(false);
 textFieldEmail.setEditable(false);
 textFieldSecurityqn.setEditable(false);
 textFieldSecurityanswer.setEditable(false);
 textFieldContactnum.setEditable(false);
 textFieldFirstName.setEditable(false);
textFieldLastName.setEditable(false);
dayList.setEditable(false);
monthList.setEditable(false);
yearList.setEditable(false);
textFieldNRIC.setEditable(false);
textFieldAddress.setEditable(false);
textFieldPostalCode.setEditable(false);
 } 
 else {
 JOptionPane.showMessageDialog(myFrame,
 "Database Error. Record not updated.", "Alert",
 JOptionPane.ERROR_MESSAGE);
 }
 }

 /**
 * Purpose: This method creates the expense record
 * in the database.
 * Input: Nil
 * Return: void
 */
 public void actionPerformedCreate(){
 // insert to database and check return value
 if (SignupDA.createhiroSIGNUP(signup)) {
 JOptionPane.showMessageDialog(myFrame,
 "Record created successfully", "Alert",
 JOptionPane.INFORMATION_MESSAGE);
 // reset text field for next record.
 // reset text field for next record.
 textFieldUsername.setText("");
 passwordField.setText("");
 textFieldEmail.setText("");
 textFieldSecurityqn.setText("");
 textFieldSecurityanswer.setText("");
 textFieldContactnum.setText("");
 textFieldFirstName.setText("");
textFieldLastName.setText("");
group.clearSelection();
textFieldNRIC.setText("");
textFieldAddress.setText("");
textFieldPostalCode.setText("");

 } 
 else
 JOptionPane.showMessageDialog(myFrame,
 "Database Error. Record not created.", "Alert",
 JOptionPane.ERROR_MESSAGE);
 }

 private boolean validateInput() {
 boolean result = false;
 String msg = "";
 int msgType = JOptionPane.ERROR_MESSAGE;
 // retrieve the user input from the text box/area provided
    String username = textFieldUsername.getText();
    String password = passwordField.getText();
    String email = textFieldEmail.getText();
    String securityqn = textFieldSecurityqn.getText();
    String securityanswer = textFieldSecurityanswer.getText();
    int contactnum = Integer.parseInt(contactnumber);
    String firstname = textFieldFirstName.getText();
    String lastname = textFieldLastName.getText();
    String gender = genderSelected;
    //FIND OUT HOW TO VALIDATE GENDER RADIO BUTTON
    String nric = textFieldNRIC.getText();
    String address = textFieldAddress.getText();
    int postalcode = Integer.parseInt(postalcode1);
    String date = dateAsString;



 if (username.length() == 0)
 msg += "Please enter Username.\n";
 if (password.length() == 0)
 msg += "Please enter password.\n";
 if (email.length() == 0)
 msg += "Please enter Email.\n";
 if (securityqn.length() == 0)
 msg += "Please enter Security Question.\n";
 if (securityanswer.length() == 0)
 msg += "Please enter Security Answer\n";
 if (contactnumber.length() == 0)
 msg += "Please enter Contact Number\n";
 if (firstname.length() == 0)
 msg += "Please enter First name\n";
 if (lastname.length() == 0)
 msg += "Please enter Last name\n";
 if (genderSelected.length() == 0)
 msg += "Please enter Gender\n";
 if (nric.length() == 0)
 msg += "Please enter NRIC\n";
 if (address.length() == 0)
 msg += "Please enter Address\n";
 if (postalcode1.length() == 0)
 msg += "Please enter Postal code\n";
 if (date.length() == 0)
     msg += "Please enter Date\n";  

 if (msg.length() == 0)
 result = true;
 else
 JOptionPane.showMessageDialog(myFrame, msg, "Alert", msgType);
 return result;
 }

 /**
 * @wbp.parser.constructor
 */
 public hiroSIGNUPPanel(JFrame mf, String action, hiroSIGNUP s){
 this(mf, action);

//display the current expense information
    signup = s;
    textFieldUsername.setText(s.getUsername());
    passwordField.setText(s.getPassword());
    textFieldEmail.setText(s.getEmail());
    textFieldSecurityqn.setText(s.getSecurityqn());
    textFieldSecurityanswer.setText(s.getSecurityanswer());
    textFieldContactnum.setText(String.valueOf(s.getContactnum()));
 textFieldFirstName.setText(s.getFirstname());
textFieldLastName.setText(s.getLastname());
//textFieldGender.setText(s.getGender());
textFieldNRIC.setText(s.getNric());
textFieldAddress.setText(s.getAddress());
textFieldPostalCode.setText(String.valueOf(s.getPostalcode()));

}

}

我的错误是

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at hiroApp.ui.hiroSIGNUPPanel.actionPerformedOk(hiroSIGNUPPanel.java:781)

在解析之前你可以尝试检查

if(contactnumber.trim().length() == 0) {
}

您可能还想使用 long,因为 int 无法存储 10 位数字的联系电话。

您的答案在错误消息中:对于输入字符串:“”

注意它是一个空字符串。

所以当你调用以下...

int contactnum = Integer.parseInt(contactnumber);

Java 如果没有任何内容,则无法将字符串解析为 int。

你可以这样处理这个错误:

try{
  int contactnum = Integer.parseInt(contactnumber);
catch(Exception e){
  System.out.println("Your Textfield is empty or filled in with letters");
}

通过这种处理,程序会捕获错误并且不会崩溃。