2016-09-29 75 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