최소 너비, 최대 너비 및 텍스트 파일 이름의 세 가지 실행 인수가 있습니다. 텍스트 파일은 하나의 긴 임의의 문자열로 채워집니다. 각 캐릭터를 그리드 지점에 넣고 싶습니다. 하지만 내가 얻은 전부는 파일의 문자열 자체입니다. 그리드는 어떻게 만들 수 있습니까?텍스트 파일의 문자열에서 격자 만들기
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로 되돌아갑니다. 내 최소 너비와 최대 너비로 결정된 격자의 문자를 원합니다. 내가 제대로 이해하면
코드 디버깅을 시도 했습니까? –
너비를 2로 설정하면 그리드는 AB, CD, E가되고 여분의 공간이 남습니다. – Jordan