声明一个无用的局部变量 [英] Declaring a useless local variable

查看:151
本文介绍了声明一个无用的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是一个奇怪的,我知道代码本身是相当无用的,但我想知道为什么我得到错误:

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();

当时没考虑变量范围,显然这没用,因为我无法使用无论如何,超过 if 。我没有得到的是为什么我收到了错误:

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();
}

编译正常。我的印象是,如果在下有1行,如果,花括号是可选的......显然还有其他考虑,或者两者都要编译或失败。

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.

有人可以向我解释,或者给我一个文件,解释为什么我不能在下声明一个局部变量if 条件没有大括号?

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?

编辑:这是完整的功能:

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';    
}


推荐答案

如果您有 if ,而 do / while 你必须用声明跟着它。声明不是声明。

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

来自 JLS 14.9 - if语句

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)

这篇关于声明一个无用的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆