简体   繁体   中英

print out once in a 2d-array at java

how can i just print out the j only once and not three times?

public static void berechneSterneProSpalte(char[][] arr) {
    for(int i = 0; i<arr.length; i++) {
        for(int j = 0; j < arr[i].length; j++) {
            System.out.print(j);
        }
        System.out.println();
    }
}

char[][] bsp3 = {{'*', 'a', '*', 'a'}, {'*', '*', '*', 'b'}, {'B', 'c', '0', 'c'}}; // Beispiel aus Aufgabenteil b
    System.out.println("Aufgabenteil b: ");
    berechneSterneProSpalte(bsp3);

Result: Aufgabenteil b: 0123 0123 0123

Add a boolean which determines if you already have it displayed, like this:

public static void berechneSterneProSpalte(char[][] arr) {
    boolean isDisplayed=false;
    for(int i = 0; i<arr.length; i++) {
        for(int j = 0; j < arr[i].length; j++) {
           if(!isDisplayed){
             System.out.print(j);
           }
        }
        isDisplayed=true;
        System.out.println();
    }
}

Perhaps this is what you needed?:

public static void berechneSterneProSpalte(char[][] arr) {
    for(int i = 0; i<arr.length; i++) {
        int starCount = 0;
        for(int j = 0; j < arr[i].length; j++) {
            if(arr[i][j]=='*'){
               starCount++;
            }
            System.out.print(j);
        }
        System.out.println("Number of Stars = " + starCount);
    }
}

char[][] bsp3 = {{'*', 'a', '*', 'a'}, {'*', '*', '*', 'b'}, {'B', 'c', '0', 'c'}}; // Beispiel aus Aufgabenteil b
    System.out.println("Aufgabenteil b: ");
    berechneSterneProSpalte(bsp3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM