简体   繁体   English

在java的二维数组中打印一次

[英]print out once in a 2d-array at java

how can i just print out the j only once and not three times?我怎么能只打印一次 j 而不是三次?

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结果: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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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