0

My code:

name = jTextFieldName.getText();
admin = Integer.parseInt(jTextFieldAdmin.getText());
anal = Integer.parseInt(jTextFieldAnalytical.getText());
creat = Integer.parseInt(jTextFieldCreative.getText());
finish = Integer.parseInt(jTextFieldFinisher.getText());

persons.addPerson(name, admin, anal, creat, finish);

persons.savePersons();

I want to make sure that name is a string and that admin, anal, creat and finish are ints between 0 and 30. I'm thinking that I should use try-catch, but I don't know exactly how to use it in this context. Any help appreciated!

GeorgeWChubby
  • 788
  • 1
  • 9
  • 17
  • Write down a separate method to validate all the values and only then add them. – Sudhanshu Umalkar Mar 15 '13 at 09:17
  • You could try http://stackoverflow.com/questions/2749521/how-to-validate-a-jtextfield or http://stackoverflow.com/questions/4926745/validate-jtextfield – SeKa Mar 15 '13 at 09:22

4 Answers4

2

try catch isn't a bad way to handle this:

try {
    name = jTextFieldName.getText();
    admin = Integer.parseInt(jTextFieldAdmin.getText());
    anal = Integer.parseInt(jTextFieldAnalytical.getText());
    creat = Integer.parseInt(jTextFieldCreative.getText());
    finish = Integer.parseInt(jTextFieldFinisher.getText());

    persons.addPerson(name, admin, anal, creat, finish);

    persons.savePersons();
} catch (NumberFormatException e) {
    // One of the integer fields failed to parse. Do something to alert the user.
}

You can then also put some bounds checking in the try part. e.g.

if (admin < 0 || admin > 30) {
    // Problem. Alert the user.
}
SteveP
  • 18,840
  • 9
  • 47
  • 60
2

Why don't you use a JSpinner instead.

tmwanik
  • 1,643
  • 14
  • 20
1

What you need is if-else which statisfies condition or ask user to input again if required.

ex -

if(admin<0 || admin>30){
  // ask user to input again.
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

Use InputVerifier for JTextField, like below

public class MyInputVerifier extends InputVerifier {
    @Override
    public boolean verify(JComponent input) {
        String text = ((JTextField) input).getText();
        // Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
    }
}

// Set input verifier to the text field
jTextField.setInputVerifier(new MyInputVerifier());
spgodara
  • 984
  • 9
  • 10