Skip to content
Advertisement

How to fully print outer loop before inner loop (Java)

My goal is to print a chart that displays “enemy” number, x and y coordinates, then their distance in respect to the other “enemies”, but with my following nested loop below, the enemy number, and coordinates are reversed with the distance numbers. I’ve tried adjusting the position of the codes, but they don’t seem to fix the issue.

public static void main(String[] args) {
    
    // array of enemy coordinates
    int[] xCoords = {1, 4, 5, 5, 7, 10};
    int[] yCoords = {3, 4, 6, 2, 5, 2};
    
    
    System.out.println("________Enemy Distance Chart________");
    System.out.println("ttttttDistance To (Kilometers)");
    System.out.println("Enemiest  X Coord  tY Coord  tE-0tE-1tE-2tE-3tE-4tE-5");
    
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6; j++) {
            double distance = Math.sqrt((yCoords[j]-yCoords[i])*(yCoords[j]-yCoords[i]) + (xCoords[j]-xCoords[i])*(xCoords[j]-xCoords[i]));
            System.out.printf("%.2ft", distance);  
        }
        // the following code below is somehow printed on the far right 
        System.out.println("E- " + i + "tt  " + xCoords[i] + "t      " + yCoords[i]); 
    }
    
    


    

Advertisement

Answer

    for (int i = 0; i < 6; i++) {
        System.out.printf("E-" + i + "tt" + xCoords[i] + "tt" + yCoords[i] + "tt");
        for (int j = 0; j < 6; j++) {
            double distance = Math.sqrt((yCoords[j] - yCoords[i]) * (yCoords[j] - yCoords[i]) + (xCoords[j] - xCoords[i]) * (xCoords[j] - xCoords[i]));
            System.out.printf("%.2ft", distance);
        }
        System.out.println();
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement