javac says int (x = 1); is not a statement then says ';' expected. What's wrong with my code?

StackOverflow https://stackoverflow.com/questions/4789282

Pergunta

I'm on a Mac Mini G4 trying to learn Java. When I try to compile "DooBee.java" by typing "javac DooBee.java" at the terminal I get two errors. This is what my terminal looks like:

> nephi-shields-mac-mini:/developer/MyProjects
> nephishields$ javac DooBee.java
> DooBee.java:5: not a statement
>                 int (x = 1);
>                 ^ DooBee.java:5: ';' expected
>                 int (x = 1);
>                     ^ 2 errors nephi-shields-mac-mini:/developer/MyProjects
> nephishields$

This is what I have typed into my "DooBee.java" file:

public class DooBee {
    public static void main (String[] args) {
        int (x = 1);

        while (x < 3) {
            System.out.print ("Doo");
            System.out.print ("Bee");
            x = x + 1;
        }

        if (x == 3) {
           System.out.print ("Do");
        }
    }
}

Have I made a mistake? Or is there something wrong with my computer? sorry if this question (or a similar one) has already been asked. I honestly tried to find an answer on my own (google searches, searching Stack Overflow, rewrote my code several times, checked my book "Head First Java" to make sure I was typing things the right way) but came up empty.

Foi útil?

Solução

The problem is that (x = 1) is an expression, not a declaration, so it can't be used to declare the variable x. Remove the parentheses and you'll have a correct declaration with initializer.

Outras dicas

The correct declaration is:

public class DooBee {
    public static void main (String[] args) {
        int x = 1;
        ...
    }
}

Remember your order of operations in Java. Items inside the parenthesis are evaluated first, so (x=1) is evaluated, which doesn't even really make sense in Java, hence the error.

Generally you'll only wrap parenthesis around casts, the clauses after an if, while, else if, else and for statement, or in situations where you want your boolean logic to be very clear.

int (x = 1);

replace that with

int x = 1;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top