gpt4 book ai didi

java - 我可以输出一个没有过多空格的数组吗?

转载 作者:行者123 更新时间:2023-12-01 21:58:48 28 4
gpt4 key购买 nike

我试图获取 .txt 文件的文本并将其信息传输到数组中,问题是,我得到了带有单词的输出,但输出的间距过大。 (数组必须为 6*7)该文件包含以下文本:“It was a beautiful Cold day in April, and the Clocks are Strike 13.”

import java.io.FileNotFoundException;
import java.util.*;

public class tryThings {


public static void main(String[] args) throws FileNotFoundException {
java.io.File file = new java.io.File("2DArray.txt");

Scanner input = new Scanner(file);
int totalRow = 6;
int totalColumn = 7;
char[][] myArray = new char[totalRow][totalColumn];
file = new java.io.File("2DArray.txt");
Scanner scanner = new Scanner(file);

for (int row = 0; scanner.hasNextLine() && row < totalRow; row++) {
char[] chars = scanner.nextLine().toCharArray();
for (int i = 0; i < totalColumn && i < chars.length; i++) {
myArray[row][i] = chars[i];
System.out.println(Arrays.toString(chars));

}
}
}
}

我需要输出位于一个 6*7 的空间中(每个空间填充一个字符或一个空格,其中是“*”)。现在,程序输出整个字符串 7 次,它应该只打印一次格式化为 6*7。如果单词与下一行重叠并且所有单词都无法放入数组中,也没关系。以下是我希望输出的外观示例: [I, t, , w, a, s, ] [a, , b, r, i, g, h] [t, , c, o, l, d , ] [d, a, y, , i, n, ] [A, p, r, i, l, ,, ] [a, n, d, , t, h, e]。

最佳答案

上述代码将为您提供预期的输出

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Sample {

public static void main(String[] args) throws FileNotFoundException {
java.io.File file = new java.io.File("2DArray.txt");

int totalRow = 6;
int totalColumn = 7;
char[][] myArray = new char[totalRow][totalColumn];
Scanner scanner = new Scanner(file);
file = new java.io.File("2DArray.txt");
int rowIndex = 0;


while (scanner.hasNextLine()) {
// Read line from file and convert to array
char[] chars = scanner.nextLine().toCharArray();

for (int charIndex = 0; rowIndex < totalRow && charIndex < chars.length; rowIndex++, charIndex =
charIndex + totalColumn) {
// Copy the X=totalColumn chars from the above array to row
System.arraycopy(chars, charIndex, myArray[rowIndex], 0,
Math.min(totalColumn, chars.length - charIndex));
}
}

for (char[] ar : myArray) {
System.out.println(Arrays.toString(ar));
}
scanner.close();
}
}

There is one thing to take care of- When First line is shorter than total number of elements matrix can fit in. It will load the next line, but the new line will be started from new row in matrix, please see below example-

 E.g. Input -   Line1: It was a bri   
Line2: ght cold day in April, and the clocks were striking thirteen.

该代码基于您提供的确认输出,需要任何更改 - 请告诉我

关于java - 我可以输出一个没有过多空格的数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58718359/

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