亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅在聲明最后一個數組時出現的神秘錯誤

僅在聲明最后一個數組時出現的神秘錯誤

慕容3067478 2021-10-27 10:01:56
聲明數組時,IDE (Eclipse) 給我一個錯誤。但是,如果我在之后立即聲明另一個數組,錯誤就會像魔法一樣轉移到下一個數組。我可以嘗試添加越來越多的數組,但我只會推遲不可避免的事情。這給我留下了兩個問題:為什么會發生錯誤以及如何修復它?import java.util.Arrays; public class BattleshipGrid {    private char[][] arr1 = new char[10][10];    private char[][] arr2 = new char[10][10];    private char[][] arr3 = new char[10][10];     private char[][] arr4 = new char[10][10];//"Syntax error on token ";", { expected    for (char[] i: arr2) {        for(char j: i) {            i[j]='X';        }    }    public static void main (String[] args) {    }}
查看完整描述

3 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

您的 for 循環必須駐留在某種方法中。


查看完整回答
反對 回復 2021-10-27
?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

For 循環本身不能在一個類中。類只是聲明的地方,而不是代碼的地方。Java 中的代碼僅在方法中。


所以你有2個解決方案。要么將您的代碼放在main方法中:


import java.util.Arrays; 

public class BattleshipGrid {

    private static char[][] arr1 = new char[10][10]; // Made it static so that

         // it would be bound to the class object itself, so that you can see

         // it from the main method which is also static and bound to the class

         // object

    private static char[][] arr2 = new char[10][10];

    private static char[][] arr3 = new char[10][10]; 

    private static char[][] arr4 = new char[10][10];


    public static void main (String[] args) {

        for (char[] i: arr2) {

            for(char j: i) {

                i[j]='X';

            }

        }


    }

}

另一個(更好)的解決方案是在 main 方法中創建一個類的實例。


import java.util.Arrays; 

public class BattleshipGrid {

    private char[][] arr1 = new char[10][10];

    private char[][] arr2 = new char[10][10];

    private char[][] arr3 = new char[10][10]; 

    private char[][] arr4 = new char[10][10];


    public void initializeTheGrid() {

        for (char[] i: arr2) {

            for(char j: i) {

                i[j]='X';

            }

        }

    }



    public static void main (String[] args) {

        BattleshipGrid grid = new BattleshipGrid();

        grid.initializeTheGrid();

    }

}


查看完整回答
反對 回復 2021-10-27
?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

嘗試這樣的事情:


public class BattleshipGrid

{

    private char[][] arr1 = new char[10][10];

    private char[][] arr2 = new char[10][10];

    private char[][] arr3 = new char[10][10]; 

    private char[][] arr4 = new char[10][10];


    public static void main ( String[] args )

    {

        for ( char[] i: arr2)

        {

            for ( char j: i)

            {

                j = 'X';

            }

        }

    }

}


查看完整回答
反對 回復 2021-10-27
  • 3 回答
  • 0 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號