0

I'm trying to create a method that validates that the user did not leave the JTextField empty. No error handling is needed, I just need to make sure it is not empty and the user entered the number of meals. I wrote the following:

private void validateMeals()
{
    if(mealsField.getText() == "")
    {
        JOptionPane.showMessageDialog(null,"You must enter number of meals",
        "Rocky Jonhs Management System", JOptionPane.ERROR_MESSAGE);
        mealsField.setText("");
    }
    nameField.requestFocus();
} //end validateMeals() method
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Fathi
  • 9
  • 1
  • 6
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – maloomeister Jan 21 '21 at 14:13

1 Answers1

0

You can do some changes to your method about the validation.

You can return boolean logic if the text is not empty and also is numeric. It is actually checking if the string cannot be parsed to integer (exact what you need)

private boolean validateMeals()
{
    try 
    {
        Integer.parseInt(mealsField.getText());
    } 
    catch (NumberFormatException e) 
    {
        JOptionPane.showMessageDialog(null,"You must enter number of meals",
                "Rocky Jonhs Management System", JOptionPane.ERROR_MESSAGE);
        nameField.requestFocus();
        return false;
    }
    return true;
} //end validateMeals() method
Melron
  • 569
  • 4
  • 10
  • This is university assessment. we are not allowed to use try catch. We just need to make sure that something has been entered into the textField. that text filed accepts integers only. i have used this for String input if(nameField.getText().compareTo("") == 0) i just need what similar to that for integer input – Fathi Jan 21 '21 at 14:44