Java需要将未指定的数字读入数组

时间:2011-09-26 16:33:46

标签: java arrays interface constructor

好的,所以我需要根据我在程序的另一部分指定的数字用整数填充数组。这就是我到目前为止所做的:

public abstract class Polygon implements Shape {


      //numSides is the number of sides in a polygon 

        int numSides; 

          //Vertices[] is the array of vertices, listed in counter-clockwise sense 

        Point[] Vertices; 
        public Polygon(Point[] Vertices){ 
                //THIS IS WHERE I NEED THE HELP, DONT KNOW WHAT TO PUT IN HERE  
            }


       public Point getPosition(){ 
           return this.Vertices[0]; 
                }

       }

先谢谢你。

抱歉缺乏信息。是的,这是一堂课。我可以看到ArrayList可能会更好。程序本身有一个接口Shape,它由类Point和类Polygon实现,它们有一个扩展了矩形的类。我们的想法是将顶点数放入一个数组中,并将Vertices [0]处的值作为多边形的位置返回。本课程的其余部分如下所示:

    public abstract class Polygon implements Shape {

       //numSides is the number of sides in a polygon 

        int numSides; 
        Point[] Vertices; 
        public Polygon(Point[] Vertices){ 
            //your code
            }


        public Point getPosition(){ 
          return this.Vertices[0];  
         } 
        }

不确定是否需要查看程序的其余部分。 再次感谢你。

4 个答案:

答案 0 :(得分:0)

你不是很清楚你需要什么,但我想你需要建构者的帮助:

public Polygon(Point[] Vertices){ 
    this.Vertices = Vertices;
    this.numSides = Vertices.length;
}

答案 1 :(得分:0)

也许这会引导你朝着正确的方向前进:

public static void main(String[] args) {
    System.out.print("how many? ");
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int[] numbers = new int[size];
    System.out.println("Enter the " + size + " numbers.");
    for (int i = 0; i < size; i++) {
        System.out.print(" " + (i + 1) + ": ");
        numbers[i] = in.nextInt();
    }
    System.out.println("Numbers entered: ");
    for (int number : numbers) {
        System.out.print(number);
        System.out.print(' ');
    }
}

正如其他人所说,问题中的更多细节将为答案带来更好的细节。此外,这闻起来像家庭作业。如果是这样,您应该将其标记为。

答案 2 :(得分:0)

由于你的问题不明确,我假设你只是想用随机整数填充你的数组 首先,您需要指定数组的大小,最好的位置是构造函数。

 public Polygon(Point[] Vertices){ 
        Vertices = new Point[i];
       //based on a number i specified in another part of the program
       // Now you can use the scanner class to fill your array, see Ryan Stewart's answer for details on using Scanner class.
    }

我希望这会有所帮助:) 欢呼声!!!

答案 3 :(得分:0)

,你需要一个优雅的数组副本:

public Polygon(Point[] Vertices)
{ 
    if (Vertices == null || Vertices.length == 0)
    {
        return;
    }

    int i = Vertices.length;
    this.Vertices = new Point[i];
    System.arraycopy(Vertices, 0, this.Vertices, 0, i);
}

之后,你可以迭代你的数组:

    ...
    for (Point point : this.Vertices)
    {
        // Use point
    }
    ...