views:

48

answers:

2

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?

+6  A: 

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);
} 
polygenelubricants
Thanks a lot. poly need some help with the below issue.http://stackoverflow.com/questions/2421760/regarding-java-command-line-arguments
Arav
+1  A: 

Declare it outside:

String items[];

if (valid) { 
    items = line.split("\",\"",15); 
} else { 
    items = line.split("\",\"",16); 
} 
String fileNamet = items[1].replaceAll("\"","").trim();
Tom
Thanks a lot for the info
Arav