以下开关中存在错误java,为什么得到“可能未初始化的变量”?我的开关块中出现编译器错误?...

I'm encountering "a variable might not have been initialized" error when using switch block.

Here is my code:

public static void foo(int month)

{

String monthString;

switch (month)

{

case 1: monthString = "January";

break;

case 2: monthString = "February";

break;

}

System.out.println(monthString);

}

The error:

Switch.java:17: error: variable monthString might not have been initialized

System.out.println (monthString);

To my knowledge this error occurs when you try access a variable you have not initialized, but am I not initializing it when I assign it the value in the switch block?

Similarly, even if the month is a compile-time constant, I still receive the same error:

public static void foo()

{

int month = 2;

String monthString;

switch (month)

{

case 1: monthString = "January";

break;

case 2: monthString = "February";

break;

}

System.out.println(monthString);

}

解决方案

If month isn't 1 or 2 then there is no statement in the execution path that initializes monthString before it's referenced. The compiler won't assume that the month variable retains its 2 value, even if month is final.

The JLS, Chapter 16, talks about "definite assignment" and the conditions under which a variable may be "definitely assigned" before it's referenced.

Except for the special treatment of the conditional boolean operators &&, ||, and ? : and of boolean-valued constant expressions, the values of expressions are not taken into account in the flow analysis.

The variable monthString is not definitely assigned prior to being referenced.

Initialize it before the switch block.

String monthString = "unrecognized month";

Or initialize it in a default case in the switch statement.

default:

monthString = "unrecognized month";

Or throw an exception

default:

throw new RuntimeExpception("unrecognized month " + month);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值