2013-04-13 188 views
-1

如何從二維數組中逐列打印字符而不是逐行打印?另外你如何獲得字符來填充數組?我知道你必須使用for循環,但我一直在獲取逐行讀取的字符串。從2d數組中打印字符java

String command = args[0]; 
    String Text = args[1]; //leters to be 

    char letters [] = Text.toCharArray(); 
    int m = Text.length(); //number of letters to be decrypted/encrypted 


    if (command.equals("-encrypt")) { 

     if (m/(int) Math.sqrt(m) == Math.sqrt(m)) { //if m is a perfect square no. eg.4,9,16 

      int RootM = (int) Math.sqrt(m); //find depth and width of grid, square therfore depth = width 
      char [][] box = new char [RootM][RootM]; //define and create grid 

     for (int i=0; i<RootM; i++) { 
      for (int j=0; j<RootM; j++) { 

       box[i] = letters; //change this to read each column 
       System.out.print(Text); //displays encrypted text 
      } 
     } 
    } 

     else if  (m/(int) Math.sqrt(m) != Math.sqrt(m)) { //non perfect square digits 

     int RootM = (int) Math.pow((Math.sqrt(m))+1,2); //overall size of 2d array (depth*width) 
     int RootN1 = (int) Math.sqrt(RootM); //length of rows & columns 

     char [][] box = new char [RootN1][RootN1]; //define dimensions of 2d array 

      for (int i=0; i<RootN1; i++) { 
       for (int j=0; j<RootN1; j++) { 
        box[j] = letters; //change this to read each column 
      System.out.println(Text); //displays encrypted text 
+0

只是增加了我的方法 – user2269083

+0

上面有什麼想法? – user2269083

+0

您的示例與二維數組無關 – Val

回答

1
char [][] box = new char [5][3];//5 rows, 3 columns 
for(int i =0;i<3; i++){ 
    for (int j = 0; j < 5; j++) {//Iterate rows 
     System.out.println(box[j][i]);//Print colmns 
    } 
} 
+0

我收到一條消息,指出 - > System.out.println(char [j] [i])上的無效表達式表示char是無效標記 – user2269083

+0

對於錯字,抱歉。參考更新 – JRR

+0

沒有回報:( – user2269083