Java While循环语法错误?

时间:2014-04-11 02:35:14

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

我正在尝试一个制作形状的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”的语法错误,=预期      - 语法错误,插入“;”去完成      FieldDeclaration

提前致谢!

2 个答案:

答案 0 :(得分:2)

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

插入';'在private static final int MAX_ROWS之后它应该有效。

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

答案 1 :(得分:2)

在上一行的结尾添加分号(&#39 ;;&#39;),如下所示:

private static final int MAX_ROWS;