有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java为什么我不能在for循环之外初始化变量的起始值?

有什么原因不能在for循环外初始化变量的起始值吗?当我这样做时:

    public static void main(String[] args) {

    int userInt = 1;
    int ender = 10;

    for (userInt; userInt < ender; userInt++) {
        System.out.println(userInt);

我收到一个语法错误,指出需要为userInt分配一个值,即使我已经为它分配了一个值1。当我这样做时:

public static void main(String[] args) {

    int userInt;
    int ender = 10;

    for (userInt = 1; userInt < ender; userInt++) {
        System.out.println(userInt);

错误消失了。这是什么原因


共 (2) 个答案

  1. # 1 楼答案

    Java for loop的通用语法如下:

    for ( {initialization}; {exit condition}; {incrementor} ) code_block;
    

    这意味着您不能只在块中写下变量名。如果你想使用一个已经定义好的变量,就让它emtpy

    这应该对你有用:

    for (; userInt < ender; userInt++) {
            System.out.println(userInt);
    }
    
  2. # 2 楼答案

    问题是for语句需要一个表达式

    根据language spec的说法:

    ForStatement:
        BasicForStatement
        EnhancedForStatement
    

    然后:

    BasicForStatement:
        for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
    
    ForStatementNoShortIf:
        for ( ForInitopt ; Expressionopt ; ForUpdateopt ) StatementNoShortIf
    
    ForInit:
        StatementExpressionList
        LocalVariableDeclaration
    
    ForUpdate:
        StatementExpressionList
    
    StatementExpressionList:
        StatementExpression
        StatementExpressionList , StatementExpression
    

    正如您看到的basic for语句一样,第一个元素是可选的初始化,即语句或局部变量声明

    该声明是以下声明之一:

    StatementExpression:
        Assignment
        PreIncrementExpression
        PreDecrementExpression
        PostIncrementExpression
        PostDecrementExpression
        MethodInvocation
        ClassInstanceCreationExpression
    

    在您的示例中userInt = 1是一个Assignment,而userIntStatementExpression列表上的任何元素都不匹配,这会导致编译错误