【问题标题】:2d char array from a file来自文件的二维字符数组
【发布时间】:2013-11-08 02:40:24
【问题描述】:

我正在尝试从文件中读取字符串,提取单个字符并使用这些字符填充 2D 字符数组。到目前为止,除了填充数组之外,我已经能够做所有事情。我在线程“main”java.lang.ArrayIndexOutOfBoundsException 中不断收到异常:错误消息。任何帮助,将不胜感激。这是我第一次使用二维数组。谢谢。 这是test.txt的内容。每个单词换行。前 2 个整数是数组的维度 4 4 文件 和 一些 信息

public class acsiiArt 
{

public static void main(String[] args) throws IOException
{
File file = new File("test.txt");
Scanner inputFile = new Scanner(file);
int x = inputFile.nextInt(); 
int y = inputFile.nextInt(); 
while (inputFile.hasNext())
{ 
char [][] array = new char [x][y];

   //char c = words.charAt(i);  
    for (int row =0; row<x;row++)
    {
        for (int col =0; col<y;col++)
        {
            String words = inputFile.nextLine();
            for (int i=0; i<words.length(); i++)

            array[x][y]=words.charAt(i);
        }
    }
}

}   
 }

【问题讨论】:

  • 请在test.txt中发布一些内容。实际上,我认为有2个地方需要修改。 1.关于2 for循环。使用变量 row 和 col。你为什么不使用它们。将 array[x][y]=words.charAt(i) 更改为 array[row][col]=words.charAt(i); 2.将以下代码放在while循环之外。字符 [][] 数组 = 新字符 [x][y];
  • 4 4 FILE WITH SOME INFO 这里是内容。每个单词是一个新行,两个整数是数组的维度。

标签: java char multidimensional-array


【解决方案1】:
for (int row =0; row<x;row++)
{
    for (int col =0; col<y;col++)
    {
        String words = inputFile.nextLine();
        for (int i=0; i<words.length(); i++)

        array[x][y]=words.charAt(i);
    }
}

array 中的索引总数为x * y。下面,您正在填写所有可能的索引

for (int row =0; row<x;row++)
{
    for (int col =0; col<y;col++)

所以当你添加这个时:

for (int i=0; i<words.length(); i++)

你乘以另一个因素words.length。所以你需要x * y * words.length 的索引数量,但你只有x * y。这就是为什么你会收到ArrayIndexOutOfBoudsException

【讨论】:

    【解决方案2】:

    我见过这样的问题,我假设xy 被初始化为前两个字符,它们代表行数和列数。如果是这种情况,则不需要第三个 for 循环 for (int i=0; i&lt;words.length(); i++)。此时您可以只引用该单词的 col 变量,因为它应该表示有多少个字符。

    所有这些仅适用于字符为矩形模式的情况,这意味着每行中的列数相同。否则,只要其中一行比最初给出的列值短,您就会得到IndexOutOfBoundsError

    编辑:如果您最终的 2d 字符数组不是矩形的,而是“锯齿状的”,则需要不同的实现。我建议使用 2d arrayList(arrayList 的 arrayList)。

    或者您可以使用第三个 for 循环保留当前的实现,但您必须确保原始 x 值代表最长的行/最多的列,然后您就可以处理每个与words.length 单独排列。您还必须对长度>x 且空格初始化为 null 的行的额外部分感到满意​​。

    【讨论】:

    • 在java中,二维数组应该可以是锯齿状的。这是java程序员应该学习如何使用的东西。
    • 好吧,我从来没有使用过锯齿状数组,这会使事情变得复杂。是的,你是对的,可以使用锯齿状数组,我应该提供有关该选项的更多信息。
    【解决方案3】:

    ArrayIndexOutOfBoundsException 表示您正在使用超出其限制的数组。所以在你的情况下:

    char [][] array = new char [x][y];
    //char c = words.charAt(i);  
    for (int row =0; row<x;row++) {
        for (int col =0; col<y;col++){
            String words = inputFile.nextLine();
            for (int i=0; i<words.length(); i++)
               array[x][y]=words.charAt(i);
        }
    }
    

    问题可能是因为您的数组大小小于输入words。问题是因为您放置了额外的循环,而您的循环本身不正确。请看下面的代码。
    所以你可以做两件事。

    1. 更改y 的值足够大,以便可以存储任何字串。
    2. 而不是循环单词的大小,你可以循环你的数组大小。

    .

    for (int row =0; row<x;row++) {   
        String words = inputFile.nextLine();
        int size = Math.min(words.length(),y);
        for (int i=0; i< size; i++)
             array[row][i]=words.charAt(i);
     }
    

    【讨论】:

      【解决方案4】:

      最简单的方法是使用ArrayList&lt;char[]&gt;。您所要做的就是为每个新行添加一个新的char[]

      ArrayList<char[]> chars = new ArrayList<>();
      while (inputFile.hasNext()){
          chars.add(inputFile.nextLine().toCharArray());
      }
      char[][] array = chars.toArray(new char[chars.size()][]);
      

      ArrayList 基本上是一个可变大小的数组。此代码获取文件中的每一行,将其转换为char[],然后将其添加到ArrayList。最后,它将ArrayList&lt;char[]&gt; 转换为char[][]

      如果您不能或不想使用ArrayList,您可以随时这样做:

      char[][] array = new char[1][];
      int a = 0;
      while(inputFile.hasNext()){
          //read line and convert to char[]; store it.
          array[a] = inputFile.nextLine().toCharArray();
      
          //if there are more lines, increment the size of the array.
          if (inputFile.hasNext()){
              //create a clone array of the same length.
              char[][] clone = new char[array.length][];
              //copy elements from the array to the clone. Note that this can be 
              //done by index with a for loop
              System.arraycopy(array, 0, clone, 0, array.length);
              //make array a new array with an extra char[]
              array = new char[array.length + 1][];
              //copy elements back.
              System.arraycopy(clone, 0, array, 0, clone.length);
              a++;
          }
      }
      

      如果你事先知道数组的维度:

      char[][] array = new char[dimension_1][];
      int a = 0;
      while (inputFile.hasNext()){
          array[a] = inputFile.nextLine().toCharArray();
          a++; //don't need to check if we need to add a new char[]
      }
      

      回应评论:

      我们知道char[][] 不能用Arrays.toString() 打印(如果我们想要内容),因为我们会得到很多char[].toString()。但是,char[][] 可以使用以下方法之一打印:

      public static String toString(char[][] array){
          String toReturn = "[\n";
          for (char[] cArray: array){
              for (char c: cArray){
                  toReturn += c + ",";
              }
              toReturn += "\n";
          }
          return toReturn + "]";
      }
      

      我个人更喜欢这个(需要import java.util.Arrays):

      public static String toString(char[][] array){
          String toReturn = "[\n";
          for (char[] cArray: array){
              toReturn += Arrays.toString(cArray) + "\n";
          }
          return toReturn + "]";
      }
      

      【讨论】:

      • 我正在尝试使用您对arrayList 建议的第一种方法。为了打印出新创建的二维数组,我只需要使用通常的 for 循环遍历每一行和每一列。
      • 是的。或者你可以制作一个自定义方法(见帖子)
      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多