Home > Software engineering >  print out once in a 2d-array at java
print out once in a 2d-array at java

Time:11-11

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

CodePudding user response:

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();
    }
}

CodePudding user response:

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);
  •  Tags:  
  • java
  • Related