points[0] = pointFiller(scanner);
当我运行该程序时,我在Can't figure out why...中收到 OutOfBoundsException
预先感谢您的回复
public class Point {
private int lineCount;
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
Point[] points = new Point[lineCount];
public void pointsCreator() {
Scanner scanner = new Scanner(System.in);
lineCount = scanner.nextInt();
System.out.println("----------------------");
System.out.println("enter points for first line: ");
points[0] = pointFiller(scanner);
for (int i = 1; i < lineCount; i++){
System.out.println("----------------------");
System.out.println("enter points for next line:");
points[i] = pointFiller(scanner);
}
System.out.println("----------------------");
System.out.println(Arrays.toString(points));
}
public static Point pointFiller(Scanner scanner) {
System.out.print(" - enter x: ");
int x = scanner.nextInt();
System.out.print(" - enter y: ");
int y = scanner.nextInt();
return new Point(x, y);
}
@Override
public String toString() {
return "Points for line {x = " + x + ", y = " + y + '}';
}
}
这是因为默认
lineCount
值初始化为零,然后您创建一个长度为零的数组:创建数组后,输入值
lineCount
。试试这样:
执行此行时,
lineCount == 0
. 在那之后,你在逻辑上离开了数组,因为 该数组的长度为零。lineCount
从控制台获取值后初始化数组。