user4272376
user4272376

Reputation:

Else without if, but really unclear why, also another error I'd like looking at

Hey guys working on a Java assignment for uni, why doesn't this work?

    if ( i <=39998)
        String digit = pictureFile.substring(i, i+1);
    else 
        String digit = pictureFile.substring(39998,39999);

It comes up with this error message: enter image description here

Upvotes: 1

Views: 62

Answers (1)

Thilo
Thilo

Reputation: 262824

What you have written is a syntax error, because an if or else without a code block in curly brackets can only take a statement, not a variable declaration.

This would compile, but is pointless:

if (i <=39998) {   // WARNING: unused variable
    String digit = pictureFile.substring(i, i+1);
} else {
    String digit = pictureFile.substring(39998,39999);
}

It makes no sense to declare the variable inside of the branches, as it is not visible outside the if. Should be

String digit;
if ( i <=39998)
    digit = pictureFile.substring(i, i+1);
else 
    digit = pictureFile.substring(39998,39999);

or

String digit = (i <= 39998)
     ?  pictureFile.substring(i, i+1)
     :  pictureFile.substring(39998,39999);

Upvotes: 9

Related Questions