【问题标题】:Java While Loop Syntax Error?Java While 循环语法错误?
【发布时间】:2014-04-11 02:35:13
【问题描述】:

我正在尝试一个塑造形状的 Java 项目,但我的 while 循环中不断出现语法错误,我无法弄清楚 - 有什么建议吗?

到目前为止,这是我的代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scan = new Scanner(System.in);

    System.out.println("Hello! I am a program that draws shapes, but YOU must tell me how big you wish me to make them!");
    System.out.println("Enter shape size: ");
    final int MAX_ROWS = scan.nextInt();

    // DIAMOND
    int spaces = 0, stars, row;

    for (row = 1; row <= (MAX_ROWS + 1) / 2; row++) {
        for (spaces = 0; spaces < MAX_ROWS - row; spaces++) {
            System.out.print(" ");
        }
        for (stars = 0; stars < row; stars++) {
            System.out.print("* ");
        }
        System.out.println("");
    }

    for (row = ((MAX_ROWS + 1) / 2); row < MAX_ROWS; row++) {
        for (spaces = 1; spaces < row; spaces++) {
            System.out.print(" ");
        }
        for (stars = 0; stars < MAX_ROWS - row; stars++) {
            System.out.print(" *");
        }
        System.out.println("");
    }
    System.out.println("Diamond, size " + MAX_ROWS + ".");

}

// HOLLOW SQUARE

int loopVariable = 0;  

private static final int MAX_ROWS

while(loopVariable < MAX_ROWS) {               <--- THIS IS THE SYNTAX ERROR LINE
    if(loopVariable == MAX_ROWS - 1 || 
            loopVariable == 0) {

        for(int x=0; x < MAX_ROWS; x++) { 
            System.out.print("* "); 
        } 
    } else { 
        for(int x=0; x < MAX_ROWS; x++ ) { 
            if(x == 0||x == MAX_ROWS-1) {
                System.out.print("* ");
            } else { 
                System.out.print(" "); 
            } 
        } 
    } 
    System.out.println();
    System.out.println("Hollow Square, size " + MAX_ROWS + ".");

    loopVariable++; 
} 

}

这些是它给我的错误:

此行有多个标记 - 标记“while”的语法错误,= 预期 - 语法错误,插入“;”去完成 字段声明

提前致谢!

【问题讨论】:

  • ; 在您的 while 循环之前的行之后。
  • 它在偏僻的地方。

标签: java syntax while-loop syntax-error nested-loops


【解决方案1】:

您没有将分号放在上一行。错误不在 while 循环行,但编译器仅在到达该行时才注意到错误。

插入一个';'在private static final int MAX_ROWS 之后,它应该可以工作。

编辑:如果您打算稍后在代码中更改“MAX_ROWS”的值,您还需要从声明中删除“final”。您不能更改“最终”值。此外,正如有人提到的,您需要对其进行初始化,例如将其设置为 0。您可以稍后更改它。

【讨论】:

    【解决方案2】:

    在上一行的末尾添加一个分号(';'),如下所示:

    private static final int MAX_ROWS;
    

    【讨论】:

    • 我认为您和我在完全相同的时间发布了完全相同的内容——查看时间戳 XD(顺便说一下 +1,因为它仍然是正确答案)
    • 我试过了,但它给了我这个错误:令牌“;”上的语法错误,{ 预计在这个令牌之后
    • 你不能有一个“final” int 然后尝试改变它(你在你的代码中这样做)。尝试只使用 private static int 并确保用一个值(即“0”)对其进行初始化。然后您可以稍后在您的代码中更改它
    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多