Karnak
Karnak

Reputation: 113

Syntax error on token "default", invalid Label

Can anyone help me with only error which I got when I was converting switch to if-else statements?

This is code where on the default: Eclipse show me error with message "Syntax error on token "default", invalid Label"

    @Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_font_style) {

    font.showDialog();
    } 
else if (id == R.id.btn_font_size) {
    break;
    fsize.show();
    default: //I got error here
    break;
}

}

This is my old code

        @Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_font_style:
        font.showDialog();
        break;
    case R.id.btn_font_size:
        fsize.show();
    default:
        break;
    }

}

Upvotes: 0

Views: 3904

Answers (1)

rgettman
rgettman

Reputation: 178263

In Java, default is a keyword, and it reserved as the default case in switch statements. Because of this, it is invalid as a normal label.

For a label, you must use an identifier that is not a reserved word. Also, break; statements that are outside of switches or loops are not allowed.

You can also add in a switch statement, because it looks like there are break; statements that look like they belong in a switch statement.

Now that I see the original switch statement, converting a default case from a switch statement to a if statement means using an else to cover the default case that none of the if conditions match. break; statements don't make sense in an if statement; they can be removed.

@Override
public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.btn_font_style) {

        font.showDialog();
    } 
    else if (id == R.id.btn_font_size) {
        // No break
        fsize.show();
    } else {  // old default case
        // Something here
    }
}

Because you happen not to have anything in the default case, no else clause should be present in the corresponding if statement.

@Override
public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.btn_font_style) {

        font.showDialog();
    } 
    else if (id == R.id.btn_font_size) {
        // No break
        fsize.show();
    }
}

Upvotes: 1

Related Questions