Reputation:
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);
}
}
Here I face a problem. when the loop continue for the second time it can add with the previous value that is in L1 list. My output for 1st iteration is like [71.0,71.0] and in the second iteration it will be [[71.0, 71.0, 13.0, 13.0], [71.0, 71.0, 13.0, 13.0]] like that. But I want a output like[ [71.0,71.0],[13.0,13.0]] provided land_no=2. How could I proceed?
Upvotes: 0
Views: 41
Reputation: 43206
Create L1
in the loop:
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);
}
}
A bit shorter:
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);
}
}
Upvotes: 1