java - 如何以这种形式填写这个数组?

标签 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

最佳答案

几个问题

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

关于java - 如何以这种形式填写这个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263437/

相关文章:

java - 尝试将字符串添加到一个字符串列表,但最终将字符串添加到两个字符串列表。

performance - 矩阵求逆的最快方法

algorithm - 极小极大评价函数

java - A-Star Pathfinding 选择错误的航路点

r - 如何绕过R中的for循环中的错误?

java - 如何在java中使用spark从AWS S3读取.xls文件?并且无法读取sheetName

java - 尝试从 Android 数据库中获取数据时 JSON 显示错误 403

javascript - for 循环内的异步函数(解析查询)

java - 数组java中表的对齐方式

Java 字符串参数星号