Search code examples
javaarraysfor-loopappendstringbuffer

looping over an array


hello i have previously used this code to loop over my array row by row, however i want to do it column by column now,would the best option be to have two for loops, i and j and then then append [j] [i]?

StringBuffer decryptedText = new StringBuffer();
         for(char [] i : array){
         for (int j = 0; j < i.length; j++) {
         if (i[j] !=0){
             decryptedText.append(i[j]);
         }
         }

        }
         decryptedText.toString();
            System.out.println("\nDecrypted Text:\n" + decryptedText );

Solution

  • This will only work if your array is not ragged

    StringBuffer text = new StringBuffer();
    int rowLen = array.length;
    int colLen = array[0].length;
    for(int a=0; a<colLen; a++)
        for(int b=0; b<rowLen; b++)
            if(array[b][a]!=0)
                text.append(array[b][a]);
    System.out.println(text.toString());