【问题标题】:Why is my for loop telling me Syntax error, insert "AssignmentOperator Expression"?为什么我的 for 循环告诉我语法错误,插入“AssignmentOperator 表达式”?
【发布时间】:2012-09-20 06:19:37
【问题描述】:

我有一些代码,如下所示:

int batchPosition = new Integer(batchBegin);

for (batchPosition;batchPosition<=batchEnd;batchPosition++)

但是我在eclipse中得到这个错误:

Syntax error, insert "AssignmentOperator Expression" to complete ForInit.

我查看了关于这个错误的各种帖子,并在谷歌上搜索了它,但我不知道为什么这是不允许的。

【问题讨论】:

  • 这也可能是因为你拼错了'batchPostion'
  • @Kiyura 原谅我的阅读障碍,我无法从我的文件中复制,所以我不得不重新编写它。

标签: java for-loop assignment-operator


【解决方案1】:

for 循环包含 4 个执行部分:

初始化、条件、执行体、递增或递减

int batchPosition = new Integer(batchBegin);  

for (batchPostion;batchPosition<=batchEnd;batchPosition++) 

你错过了初始化部分。

for 之前完全忽略它,你已经初始化了

for (;batchPosition<=batchEnd;batchPosition++) 

for 之前的行移到for 内部

for (int batchPosition = new Integer(batchBegin);batchPosition<=batchEnd;batchPosition++) 

但是,在后一种情况下,您将无法在 for 范围之外使用 batchPosition

【讨论】:

    【解决方案2】:

    batchPosition 本身不是有效的初始化语句 - 您可以直接跳过它:

    int batchPosition = new Integer(batchBegin);
    
    for (; batchPosition <= batchEnd; batchPosition++)
    

    但如果您不需要在循环后访问batchPosition,最好尽可能减少变量范围:

    for (int batchPosition = new Integer(batchBegin); batchPosition <= batchEnd; batchPosition++)
    

    【讨论】:

      【解决方案3】:

      出于某种原因,Java 或 Eclipse(或麻烦)不喜欢这部分循环:

      for (batchPostion....
      

      它期望用于计数位置的变量 (batchPosition) 在循环头中初始化for(f irst;only when;repeat) 部分。)我猜这是因为希望它只在循环本地。

      要修复,只需将您的作业移到标题中,如下所示:

      for (int batchPosition = new Integer (batchBegin);batchPosition<=batchEnd;batchPosition++)
      

      没有那么漂亮,但它会起作用。

      【讨论】:

        猜你喜欢
        • 2018-10-09
        • 1970-01-01
        • 1970-01-01
        • 2016-12-13
        • 2017-07-08
        • 2012-07-11
        • 2019-12-07
        • 2011-10-14
        • 1970-01-01
        相关资源
        最近更新 更多