Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

program prints only last element in array

Why does my program only prints the last element when stored in the array, but when n.getAdjacentNodes().get(p) is printed in the list individually everything works fine. Why doesn’t it print the first element?

OUTPUT
ex: see output, why doesn’t it print 386.18 instead of 381.42

Also can someone help me to print all the node values in the array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

double[][] dist = new double[10][10];
        for (Node n: nodes) {
            System.out.println("");
            for (Node p: n.getAdjacentNodes().keySet()){
                System.out.print("" + n.getName() + " to  " + p.getName() + ": " + String.format("%.2f", n.getAdjacentNodes().get(p)));
                System.out.print("     ");
                //print individually
                System.out.println(n.getAdjacentNodes().get(p));
                
                dist[0][1] = n.getAdjacentNodes().get(p);
               
            }
        }
        //Prints only last element
        System.out.println(Arrays.deepToString(dist).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

>Solution :

double[][] dist = new double[10][10];

int x = 0, y = 0;


    for (Node n: nodes) {
        System.out.println("");
        for (Node p: n.getAdjacentNodes().keySet()){
            System.out.print("" + n.getName() + " to  " + p.getName() + ": " + String.format("%.2f", n.getAdjacentNodes().get(p)));
            System.out.print("     ");
            //print individually
            System.out.println(n.getAdjacentNodes().get(p));
            
            dist[x++][y++] = n.getAdjacentNodes().get(p);
           
        }
    }
    //Prints only last element
    System.out.println(Arrays.deepToString(dist).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading