在 switch case 中重新实例化变量 [英] Re-instantiating variables in switch case

查看:40
本文介绍了在 switch case 中重新实例化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在每种情况下都创建具有相同名称的变量.例如,在下面的代码中,在 case 3 中,它会抱怨 String name 已经存在——但为什么会这样呢?Case 1 从来没有也永远不会被调用.

Why I cannot create variables in a each case with same name. For example, from the code below, in case 3 it will complain that String name already exists - but why would it? Case 1 has never been and will never be called.

我不想从 switch-case 中提取定义.那么为什么使用 if 语句可以在每种情况下定义相同的名称,但在 switch-case 中却不能?

I would not want to extract the definitions out of the switch-case. So why using if statements it lets to define same names in each case, but in switch-case it doesn't?

这是一个带有 switch case 的简单 Java 代码:

Here is a simple Java code with a switch case:

int type = 3;

switch (type) {
    case 1:
        String name = (String) respone.get("name");
        user.setName(name);
        break;
    case 2:
        String surname = (String) respone.get("surname");
        user.setSurname(surname);
        break;
    case 3:
        String name = (String) respone.get("name");
        user.clearName(name);
        break;
    default:
        ...
}

推荐答案

在不同的块中编写每个 case 语句:

Write each case statement in a different block:

switch (type) {
    case 1: {
        String name = (String) respone.get("name");
        user.setName(name);
        break;
    }
    case 2: {
        String surname = (String) respone.get("surname");
        user.setSurname(surname);
        break;
    }
    ...
}

这篇关于在 switch case 中重新实例化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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