public void landmarks(int land_no){
ArrayList<Double> L1=new ArrayList<>();
ArrayList<ArrayList<Double>>L3=new ArrayList<>();
for(int i=0;i<land_no;i++){
double a=Math.random()*100;// generate some random numbers
double b=Math.round(a);//round off this numbers
L1.add(b);// Add this number into the arraylist
L1.add(b);//Here I add b two times in the arraylist because I want to create a point which has a x coordinate value and a y co ordinate value . As per my code both values are same. like(23,23),(56,56)
L3.add(i,L1);//Now adding those points into another ArrayList type Arraylist
System.out.println(i);
System.out.println(L3);
}
}
我在这里面临一个问题。当循环第二次继续时,它可以添加L1列表中的先前值。第一次迭代的输出类似于[71.0,71.0],在第二次迭代中,它将是[[71.0,71.0,13.0,13.0],[71.0,71.0,13.0,13.0]]。但我想要一个像[[71.0,71.0],[13.0,13.0]]这样的输出,提供land_no = 2。我该怎么办?
答案 0 :(得分:1)
在循环中创建L1
:
public void landmarks(int land_no) {
ArrayList<List<Double>> L3 = new ArrayList<>();
for(int i = 0; i < land_no; i++) {
double a = Math.random() * 100;
double b = Math.round(a);
List<Double> L1 = new ArrayList<>(); // <-- HERE
L1.add(b);
L1.add(b);
L3.add(i, L1);
System.out.println(i);
System.out.println(L3);
}
}
稍短一些:
public void landmarks(int land_no) {
ArrayList<List<Double>> L3 = new ArrayList<>();
for(int i = 0; i < land_no; i++) {
double a = Math.random() * 100;
double b = Math.round(a);
L3.add(i, Arrays.asList(b, b)); // <-- HERE
System.out.println(i);
System.out.println(L3);
}
}