2016-09-29 39 views
0

我正在使用的代碼如下。我覺得這應該很簡單,但本週的焦點集中在難以置信的困難時刻,需要一些幫助。類和2維數組

我無法在嵌套for循環中正確設置pt.x或pt.y的值。 IDEA告訴我該符號無法解析。該類是從包中只識別該類的另一個java文件標識的。其計算方法如下:

public class pointClass { 
    class point{ 
     int x; 
     int y; 
     int z; 
    } 
} 

(添加文本來證明這些是2個獨立的文件)

這是一個課堂作業,但我不共享整個分配,正是我需要幫助。我在努力學習,沒有爲我完成任何事情。

public class main { 
    public static void main (String args[]){ 

     ArrayList<pointClass.point> pointlist = new ArrayList<>(); 

     //Creating map 
     int row = 40; 
     int col = 40; 
     int [][] bigarray = new int [row] [col]; 

     //iterating through map 
     for (int i = 0; i < row; i++;){ 
      for (int j=0; j< col; j++){ 
       pointClass pt = new pointClass.point; 
       pt.x = row; 
       pt.y = col; 
       pt.z = ;//RNG HERE// 

      } 
     } 

我該如何更正確地識別這些類屬性?對於上下文,該代碼創建一個40x40數組,併爲每個數字分配一個隨機值。將添加另一個代碼節以打印2D數組。

+2

:考慮使用以下方法嗎? – shmosel

回答

0

這裏似乎沒有對嵌套類的需求。考慮使用以下內容:

public class Point { 
    int x; 
    int y; 
    int z; 
} 

現在讓我們來看看您的語法錯誤。大多數都很簡單,但值得討論。

public class Main { 
    public static void main(String args[]){ 

     ArrayList<Point> pointlist = new ArrayList<>(); //Now that we aren't using a nested class, Just <Point>    

     //Creating map 
     int row = 40; 
     int col = 40; 
     int [][] bigarray = new int [row] [col]; 

     //iterating through map 
     for (int i = 0; i < row; i++){ //No semicolon after i++ 
      for (int j=0; j< col; j++){ 
       Point pt = new Point(); //Calling a constructor is a method, hence() 
       pt.x = j; //You probably mean j and k here, not row and col (which don't change) 
       pt.y = k; 
       pt.z = 0;//RNG HERE// //Not sure what you mean here, but you can set pt.z to whatever you want 

       //You created pointlist, but never add to it. Did you mean to? 
       pointlist.add(pt); 
      } 
     } 
    } 
} 

我剛剛測試過上述代碼,它編譯和運行正確。也就是說,你可以在風格上做得更好。這裏有一些提示。

  • 類名以大寫字母開頭。 Point,而不是pointPointClass,而不是pointClass
  • 非最終/可變字段應該是私有的。因此,您的Point類儘管是正確的,但卻是相當糟糕的做法(其原因在其他地方有很好的記載)。你爲什麼要使用一個嵌套類

    public class Point { 
        private int x; 
        private int y; 
        private int z; 
    
        public Point(int x, int y, int z) { 
         this.x = x; 
         this.y = y; 
         this.z = z; 
        } 
    
        public int getX() { return x; } 
        public int getY() { return y; } 
        public int getZ() { return z; } 
    } 
    
+0

謝謝,Mshnik。我覺得我不應該犯這些錯誤,但是,可惜的是,40小時的工作,認證預測和學校做了我的大腦。Upvote獎,我的代表太低了,無法計數。 – Dylan