switch 语句中的重复局部变量 [英] Duplicate local variable in switch statement

查看:58
本文介绍了switch 语句中的重复局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Eclipse 时遇到此错误.

I was getting this error using Eclipse.

复制局部变量披风

我真的不明白为什么我会收到这样的错误.这是我的代码:

I really don't understand why I was getting such an error. This was my code:

switch (frame) {  // frame is an integer
case 0:
    Sprite cape = modules.get(Module.CAPE);
    //cape.setRegion(region);
    cape.translateY(+1);
    break;
case 1:
    Sprite cape = modules.get(Module.CAPE);
    //cape.setRegion(region);
    cape.translateY(-1);
    break;
default:
    throw new IllegalArgumentException(
            "Undefined frame number: " + frame);
}

为什么 cape 变量不是每个 case 的局部变量,而是 switch 语句的变量?

Why is it not true that the cape variable is local to each case, but instead to the switch statement?

推荐答案

为什么 cape 变量对于每种情况都是局部的,但为什么不正确?而不是 switch 语句?

Why is it not true that the cape variable is local to each case, but instead to the switch statement?

因为 JLS 是这么说的

(第 14.4 节)中局部变量声明的范围是声明出现的块的其余部分,从它的开始自己的初始化程序,并在右侧包括任何其他声明符局部变量声明语句.

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

关于开关

switch 语句的主体称为 switch 块.

The body of a switch statement is known as a switch block.

case 不定义范围.switch 块定义了一个新的作用域.

A case does not define a scope. It's the switch block that defines a new scope.

这篇关于switch 语句中的重复局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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