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。我该如何进行?
最佳答案
在循环中创建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);
}
}