Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

java - Declaring a useless local variable

So this is an odd one, I know the code itself is fairly useless, but what I'm wondering why I get the error:

I was writing some code, I had written this:

if(scan.hasNextInt())
    int row = scan.nextInt();

Wasn't thinking about variable scope at the time, obviously this is useless because I can't use row past the if anyway. What I don't get is why I got the error I did:

> javac hw.java
hw.java:25: '.class' expected
    int row = scan.nextInt();
        ^
hw.java:25: not a statement
    int row = scan.nextInt();
    ^    
hw.java:25: illegal start of expression
    int row = scan.nextInt();
            ^
hw.java:25: ';' expected
    int row = scan.nextInt();
                  ^

Now if I just modify that if check to:

if(scan.hasNextInt()) {
    int row = scan.nextInt();
}

It will compile fine. I was under the impression that if there was 1 line under the if the curly brackets were optional... clearly there are other considerations as well or both would either compile or fail.

Could someone explain to me, or point me to a document that explains why I can't declare a local variable under the if conditional without the curly brackets?


EDIT: Here's the full function:

public static char getinput() {
    System.out.println("Where do you want to go? (row column)");
    Scanner scan = new Scanner(System.in);
    if(scan.hasNextInt())
        int row = scan.nextInt();
    String input = scan.next();
    System.out.println(input);
    return 'a';    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a if, for, while, do/while you must follow it with a statement. A declaration is not a statement.

From JLS 14.9 - The if Statement

IfThenStatement:
    if ( Expression ) Statement

IfThenElseStatement:
    if ( Expression ) StatementNoShortIf else Statement

IfThenElseStatementNoShortIf:
    if ( Expression ) StatementNoShortIf else StatementNoShortIf

I assume they do this because any variable you declare couldn't be used as it would be out of scope immediately (except the same declaration)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...