簡體   English   中英

在Java中尋找一種在每次迭代中將(x,y)輸入到數組的方法

[英]Looking for a method in java to input (x,y) to an array on every iteration

我正在尋找在Java中數組調用的每個實例上添加一個點(x,y),這就是我想要聲明的數組

int [] weight = new int[100];

我希望在下一步中添加值

 weight.add(3,4);
 weight.add(5,6);

我正在尋找的想法是當我進行這樣的迭代時

for(int i =0;i< weight.length;i++)
     print "Weight"+i+ "has"+ weight[i] 

它應該打印

       Weight 0 has (3,4);

我會為每個包含x和y坐標的點創建一個類。

class Point{
    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }
}

然后,不制作一個整數數組,而是制作一個點數組...類似...

//create array of points size 100
Point [] weight = new Point[100];

//add point to array
int i = 0; //set this to the index you want the point at
weight[i] = new Point(0, 0); //add whatever point you want to index i

//then you can loop through your array of points and print them out
for (int i = 0; i < weight.length; i++){

    System.out.println("Weight " + i + " has (" + weight[i].x + "," + weight[i].y + ");\n"
}

我認為將x和y坐標抽象為Point類是更好的設計。 編程時,它將幫助您更好地記住數據。 此外,您可以將方法添加到您的點類中,例如double distance(Point other)以返回兩個點之間的距離...

創建一個私有內部類Point為:

private static class Point {
    int x;
    int y;
    //...........
}

然后,為每個x, y對創建一個點對象並將其weight

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM