我正在使用的代码如下。我觉得这应该很简单,但我本周难以集中精力并需要一些帮助。
我无法在嵌套的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数组。
答案 0 :(得分: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
,而不是point
。 PointClass
,而不是pointClass
。非final / mutable字段应该是私有的。因此,你的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; }
}