如何以这种形式填充此数组?

时间:2017-02-16 01:57:04

标签: java algorithm for-loop encryption

我希望我的程序能以某种方式输出,我怎么能这样做?到目前为止,我的代码给了我错误的东西。

这是我的.txt文件:

ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO

这是我的java文件:

import java.io.*;

public class EncryptDecrypt {

    public static void encrypt() throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("cryptographyTextFile.txt"));
        String line = in.readLine();

        char[][] table = new char[6][5];

        // fill array
        for(int i = 0; i < 6; i++) {
            for(int j = 0; j < 5; j++) {
                while(table[i][j] < 6) {
                    table[i][j] = line.charAt(j);
                }
            }
        }

        // print array
        for(int i = 0; i < 6; i++) {
            for(int j = 0; j < 5; j++) {
                System.out.println(table[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) throws IOException {
        encrypt();
    }
}

我将如何打印此.txt文件:

ABCDE
GHIJK
MNOPQ
STUVW
XYZOO
OOOOO

1 个答案:

答案 0 :(得分:2)

一些问题

    String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";

    char[][] table = new char[6][5];
    int counter = 0;
    // fill array
    for(int i = 0; i < 6; i++) {
        for(int j = 0; j < 5; j++) {
            table[i][j] = line.charAt(counter++);  // need to increment through the String
        }
    }

    // print array
    for(int i = 0; i < 6; i++) {
        for(int j = 0; j < 5; j++) {
            System.out.print(table[i][j] + " ");  // not println
        }
        System.out.println();
    }

<强>输出

A B C D E 
F G H I J 
K L M N O 
P Q R S T 
U V W X Y 
Z O O O O 

虽然更可扩展的方式是link

    String line = "ABCDEFGHIJKLMNOPQRSTUVWXYZOOOOOOO";
    String lines [] = line.split("(?<=\\G.....)");
    for (String l : lines) {
        System.out.println(l);
    }