1

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    When you declare a variable (for eg: when you are declaring `x` of type integer) you don't put then in `(..)` you simply write `type variablename = value` so `int x = 1;` You do need the brackets when you want to use that variable in conditional statements like Ifs and Whiles and soon...Hope this helps :) – VoodooChild Jan 25 '11 at 02:07

4 Answers4

5

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.

Jeffrey Hantin
  • 35,734
  • 7
  • 75
  • 94
2

The correct declaration is:

public class DooBee {
    public static void main (String[] args) {
        int x = 1;
        ...
    }
}
vz0
  • 32,345
  • 7
  • 44
  • 77
2

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.

Ashton K
  • 875
  • 1
  • 8
  • 18
  • It actually has to do with accepted grammar and not order of evaluation, but an acceptable answer none-the-less. –  Jan 25 '11 at 03:03
1
int (x = 1);

replace that with

int x = 1;
thkala
  • 84,049
  • 23
  • 157
  • 201
Eddie
  • 11
  • 1