在Java中创建一个点类,并编写一个程序来创建10个随机点。请帮助我。
double[] location = new double [10];
for (int i=0; i<10 ;i++){
location[i]=Math.random();
System.out.println(Math.random());
答案 0 :(得分:1)
欢迎使用StackOverflow。
假设您粘贴了确切的作业,那么您会误解了所给的任务。您需要创建一个Point
类。它需要存储坐标,并且您需要在某种空间内创建“随机”点。 (我假设是二维空间)
首先是2D空间的(最原始的)public class Point {
// define your coordinates, so you can later assign them (randomly)
public double x;
public double y;
// this is a constructor. It allows you to create new instances of Point.
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
类:
public static void main(String[] args) {
// Making a list to store the points in
List<Point> points = new ArrayList<>();
// Loop to create 10 Points.
for (int i = 0; i < 10; ++i) {
points.add(new Point(Math.random(), Math.random()));
}
// One possible way to print all the Points in the list.
points.forEach(point -> System.out.println(point.x + ", " + point.y);
}
现在您可以创建随机点并打印它们:
{{1}}
答案 1 :(得分:-1)
您的代码完全符合您的要求,唯一缺少的是类定义和将代码包装在其中的方法。
public class PointCreator {
public double[] generatePoints() {
double[] location = new double [10];
for (int i=0; i<10 ;i++){
location[i]=Math.random();
}
return location;
}
}
如果要使用二维点,则需要使用double[][]
或(最好)创建一个包含该点的包装器类:
public class Point {
private int x, y;
public Point (int x, int y) {
this.x = x;
this.y = y;
}
//getters
}
然后执行:
public class PointCreator {
public Point[] generatePoints() {
Point[] location = new Point[10];
for (int i=0; i<10 ;i++){
location[i]= new Point(Math.random(), Math.random());
}
return location;
}
}