0
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?

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

now if I store L3 in a two dimensional array how could I store it? double [][] b2= new double[L3.size()][L3.size()]; for (int i =0; i < L3.size(); i++) {for(j=0;j<L3[0].size;j++){ b2[i][j] = L3[i][j];}} But it is not working.Can you suggest me a way?