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

我正在尝试获取.txt文件的文本并将其信息传输到数组,麻烦的是,我得到带有单词的输出,但是输出的间距过大。 (数组必须为6 * 7)文件中包含以下文本:“四月真是寒冷的一天,钟声敲响了十三点。”

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]。

yexi831020zqymy 回答:我可以输出没有过多空格的数组吗?

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

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],Math.min(totalColumn,chars.length - charIndex));
      }
    }

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

有一件事要照顾-当第一行短于   矩阵可以容纳的元素总数。它将加载下一个   行,但是新行将从矩阵中的新行开始,请参见下面的示例-

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

代码基于您提供的确认输出,需要进行任何更改-让我知道

本文链接:https://www.f2er.com/3156846.html

大家都在问