1

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?

1
  • Please format code: stackoverflow.com/editing-help If you were a newbie, I'd do it for you, but this is your 24th question -- you should be on this by now. :-) Commented Mar 10, 2010 at 10:06

2 Answers 2

6

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);
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. poly need some help with the below issue. stackoverflow.com/questions/2421760/…
1

Declare it outside:

String items[];

if (valid) { 
    items = line.split("\",\"",15); 
} else { 
    items = line.split("\",\"",16); 
} 
String fileNamet = items[1].replaceAll("\"","").trim();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.