Skip to content
Advertisement

Else If statement not recognizing If statement [closed]

I’m getting an error in my code where one of the else if statements is throwing an error that there is no if statement even though there is

I checked other questions but all of them had the same issue where there was a semicolon after the if statement.

int ans = 0;
String[] array = s.split("");
for(int i = 0; i < array.length;){
    if(array[i] == ""){ans+=0; i++;}
    else if(array[i] == "I" && array[i+1] == "V"){ans+=4; i+=2;}
    else if(array[i] == "I" && array[i+1] == "X"){ans+=10; i+=2;}
    else if(array[i] == "V"){ans+=5; i++;}
    else if(array[i] == "X" && array[i+1] == "L"){ans+=40; i+=2;}
    else if(array[i] == "X" && array[i+1] == "C"){ans+=90; i+=2;}
    else if(array[i] == "L"){ans+=50; i++;};
    //Error is on this line below
    else if(array[i] == "C" && array[i+1] == "D"){ans+=400; i+=2;}
    else if(array[i] == "C" && array[i+1] == "M"){ans+=900; i+=2;}
    else if(array[i] == "C"){ans+=100; i++;}
    else if(array[i] == "D"){ans+=500; i++;}
    else if(array[i] == "M"){ans+=1000; i++;}
}

Advertisement

Answer

Your problem lies in a pesky semicolon:

else if(array[i] == "L"){ans+=50; i++;};

That trailing semi-colon says your entire conditional statement is ending. Thus there’s no associated if for your next else.

Also note that if you’re not otherwise screening, i can go to array.length - 1, which means i+1 would be an out of bounds array access.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement