mrsus
mrsus

Reputation: 5486

changing value of a variable inside catch block

Here's the code:

public static String removeDateFromString(String txt) {
    String dateRemovedString = new String();
    String[] str = txt.split("-");

    for(int i=0; i<str.length; i++) {

        SimpleDateFormat format = new SimpleDateFormat("dd MMM");
        try {
            format.parse(str[i]);
        } catch(ParseException e) {
            dateRemovedString.concat(str[i]);
        }
    }
    return dateRemovedString;
}

For,

input text:Cricket Match - 01 Jul

output text:"" (empty String)

But I want, output:Cricket Match

What should I do?

Upvotes: 3

Views: 1704

Answers (2)

Lewis.He
Lewis.He

Reputation: 91

If you are sure about the input text format, then don't bother to hit the exception.

Simply extract the part you are interested using split or RegExp and then process it

Upvotes: 0

johnchen902
johnchen902

Reputation: 9599

String is immutable:

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

dateRemovedString = dateRemovedString.concat(str[i]);

StringBuilder is mutable. StringBuilder is used to build a String. Use StringBuilder instead in this case. Example usage:

StringBuilder dateRemovedString = new StringBuilder();
dateRemovedString.append(str[i]);
return dateRemovedString.toString();

Upvotes: 14

Related Questions