gpt4 book ai didi

java - 从文本文件中的字符串创建网格

转载 作者:太空宇宙 更新时间:2023-11-04 14:27:59 25 4
gpt4 key购买 nike

我有三个运行参数,分别是最小宽度、最大宽度和文本文件名。文本文件充满一长串随机字符。我想将每个角色放入一个网格点中。但我得到的只是文件中的字符串本身。我如何制作网格?

class GridCipher{

static int minGridWidth;
static int maxGridWidth;

static File inputFile;

public static void main(String[] args) throws FileNotFoundException {
if (handleArguments(args))
processInput();

}

static final String usage = "Usage: GridWriter min_width max_width input_file_name";

static boolean handleArguments(String[] args) {
// Check for correct number of arguments
if (args.length != 3) {
System.out.println("Wrong number of command line arguments.");
System.out.println(usage);
return false;
}

try {
minGridWidth = Integer.parseInt(args[0]);
maxGridWidth = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
System.out.println("min_width and max_width must be integers.");
System.out.println(usage);
return false;
}

inputFile = new File(args[2]);
if (!inputFile.canRead()) {
System.out.println("The file " + args[2] + " cannot be opened for input.");
return false;
}

return true;
}

static void processInput() throws FileNotFoundException {
Scanner input = new Scanner(inputFile);
String line = input.nextLine();
int length = line.length(); // number of characters.

// Try each width in the appropriate range
for (int width = minGridWidth; width <= maxGridWidth; width++) {
// Determine heigth of grid
int height = line.length() / width;

// Add one to height if there's a partial last row
if (line.length() % width != 0)
height += 1;

loadUnloadGrid(line, width, height);
}
}

static void loadUnloadGrid(String line, int width, int height) {
char grid[][] = new char[height][width];

// Determine number long columns
int longColumn = line.length() % width;
if (longColumn == 0)
longColumn = width;

//Load the input data into the grid by column
int charCount = 0;
for (int c = 0; c < width; c++) {
for (int r = 0; r < height; r++) {
if (r < height - 1 || c < longColumn) {
grid[r][c] = line.charAt(charCount);
charCount += 1;
}
}
}

// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}
// Special handling for last row
for (int c = 0; c < longColumn; c++) {
System.out.print(grid[height - 1][c]);
}
System.out.println("\"");
}
}

如果文本文件有 ABCDE,我就返回 ABCDE。我想要网格中的字符由我的最小和最大宽度确定。

最佳答案

如果我理解正确的话,你希望 ABCDEFG 进入

 A B C
D E F
G

但是在屏幕上写入的片段中您错过了换行符

// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
}

应该是

// Output data from the grid by rows
for (int r = 0; r < height - 1; r++) {
for (int c = 0; c < width; c++) {
System.out.print(grid[r][c]);
}
System.out.println();
}

关于java - 从文本文件中的字符串创建网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26459271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com