Hello, I'm trying to write a method that resets a string to a default value (previously defined in a class) if the value inputted is not a valid.

Because I know the format or structure of a valid input, I should easily be able to do this. The string is a date with the following structure
##-##-##, and using the split() method in the String class, I can create an array with three elements provide i use the hyphen as my delimiter. All that remains is to check if each element has a length that is exactly 2.

Does that sound like it would work? Because it doesn't. I'm not sure what to do about this because me reasoning seems to be correct, and I can't find any error in my code. The method is below.

public void setDate(String b) 
  { 
    String[] a = b.split("-");
    for(int i = 0; i < a.length; i++) 
    { 
      if(a[i].length() != 2) { this.date = "00-00-00";}
      else { this.date = b;}
    }
  }

Edited 6 Years Ago by rue64ja: n/a

It looks like it should work but have you tested it? Also you will need to take each element of the array and check if it is between 1-12 and 1-31. You should also check depending on the month if it has the irght number of days. (April cannot have 31 days). Also depending on the year and the month you might want to check if February has the right nunmer of days.

For validating String that represent dates better use this:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
sdf.setLenient(false);

String input = "something";
try {
   Date d = sdf.parse(input); // if the string is not a dd-MM-yy date it will throw an exception

   this.date = input;
} catch (ParseException e) {
  // error
  this.date = "00-00-00"
}

Hey, thanks! I'm not up to speed with the classes you've used or with coding for exceptions, but I'll go through the API and see what I can learn… Thanks again.

Oh, another quick question… are the methods and constructors given in the API specific enough? I shouldn't run into any issues if I stick with those right?

Edited 6 Years Ago by rue64ja: n/a

Hey, thanks! I'm not up to speed with the classes you've used or with coding for exceptions, but I'll go through the API and see what I can learn… Thanks again.

Oh, another quick question… are the methods and constructors given in the API specific enough? I shouldn't run into any issues if I stick with those right?

The API is the official reference. This is where you needto look. It explains exactly what are the arguments of a method/constructor and what they return and most importantly what they do exactly. So don't assume that you know what a method does, just read the API for a more detailed description.

This question has already been answered. Start a new discussion instead.