Reputation: 5247
I have the below String assignment statement
String items[] = line.split("\",\"",15);
String fileNamet = items[1].replaceAll("\"","").trim();
I need to introduce a new if statement
if (valid) {
String items[] = line.split("\",\"",15);
} else {
String items[] = line.split("\",\"",16);
}
String fileNamet = items[1].replaceAll("\"","").trim();
Now items becomes local to the if loop and is giving me compilation errors. How can I declare the items array outside the if loop?
Upvotes: 1
Views: 299
Reputation: 383676
This is the kinds of scenarios where the ternary operator excels at (JLS 15.25 Conditional Operator ?:)
String[] items = line.split("\",\"", (valid ? 15 : 16));
No code is repeated, and once you get used to it, it reads much better.
That said, you can also pull out the declaration outside of the if
if that's what you're more comfortable with.
String[] items;
if (valid) {
items = line.split("\",\"",15);
} else {
items = line.split("\",\"",16);
}
Upvotes: 6
Reputation: 13310
Declare it outside:
String items[];
if (valid) {
items = line.split("\",\"",15);
} else {
items = line.split("\",\"",16);
}
String fileNamet = items[1].replaceAll("\"","").trim();
Upvotes: 1