if语句中的Java变量范围

if语句中的Java变量范围

本文介绍了if语句中的Java变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下代码的编译错误:

I received a compilation error for the following code:

if(true)
    int a = 10;
else
    int b = 20;

如果将其更改为以下代码,则没有编译错误:

If I change it to the following code, then there is no compilation error:

if(true) {
    int a = 10;
}
else {
    int b = 20;
}

为什么第一个语法错误,以及从哪种语言标准开始?

Why is the first syntax wrong, and from what language standard?

推荐答案

Java规范指出,if-then-else语句具有以下形式:

The Java specification says that an if-then-else statement is of the following form:

IfThenElseStatement:
    if ( Expression ) StatementNoShortIf else Statement

StatementStatementNoShortIf可以是各种各样的东西,包括块(用大括号括起来的代码),赋值(已声明的变量),其他if语句等.

Where Statement and StatementNoShortIf can be various things including blocks (code surrounded with braces), assignments (to already declared variables), other if statements etc.

值得注意的是,该列表中缺少声明语句(例如int a;int a = 10;),因此会出现编译错误.

Of note is that declaration statements (e.g. int a; or int a = 10;) are missing from that list, thus you get a compilation error.

有关完整列表,您可以在此处阅读Java规范: http://docs.oracle.com/javase/specs/

For the full list, you can read the Java specification here:http://docs.oracle.com/javase/specs/

这篇关于if语句中的Java变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 14:36