Java“复制局部变量” - 是Java或Eclipse中抛出的错误? [英] Java "Duplicate local variable" - is the error thrown in Java or Eclipse?

查看:201
本文介绍了Java“复制局部变量” - 是Java或Eclipse中抛出的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中:

private static void example() {
    String inputString = "test";
    switch (inputString) {
        case "test":
            String outputString = "The string said test";
        case "not test":
            String outputString = "The string did not say test";
    }
    /*Do stuff with ouputString*/        
}

Eclipse突出显示 Casenot test之后的错误,错误重复的局部变量outputString 。但是,由于它们位于开关语句的单独分支中,因此它们并不实际上处于冲突状态,因为一次只能生效一次。

Eclipse highlights the line after Case "not test" with the error Duplicate local variable outputString. However, since they are in separate branches of the switch statement, they are not actually in conflict, as only one can ever be in effect at a time.

显然,在这种情况下,我可以通过在开关之外移动 outputString 声明来解决问题。 code>语句。但是,在更复杂的程序中,解决方案可能不是那么简单。

Obviously, in this case I could get around the problem by moving the outputString declaration outside the switch statement. However, in more complex programs, the solution might not be so simple.

这是Eclipse抛出的一个错误,以防止编程技术不好,还是实际的Java错误?

Is this simply an error thrown by Eclipse to prevent poor programming technique, or an actual Java error?

我对Java很新颖,所以如果这是一个新手问题,我很抱歉 - 我有一个谷歌的重复的局部变量Java,但到目前为止人们要求帮助解决问题(通常的解决方案是重命名一个变量),而不是讨论问题本身。

I'm very new to Java, so apologies if this is a newbie question - I've had a google for "Duplicate local variable Java", but so far all that turned up were people asking for help with fixing the problem (the usual solution being to rename one of the variables), not discussion of the problem itself.

推荐答案

在java中每个switch语句的变量范围是整个switch语句。

The scope of a variable in each case of a switch statement in java is the whole switch statement.

您可以通过添加来创建更多的嵌套作用域括号如下:

You can create further nested scopes by adding braces like so:

 switch (inputString) {
        case "test": {
            String outputString = "The string said test";
            break;
        }
        case "not test": {
            String outputString = "The string did not say test";
            break;
        }
    }

这篇关于Java“复制局部变量” - 是Java或Eclipse中抛出的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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