从文本文件中添加数组值并打印它们

时间:2014-12-22 18:59:39

标签: java arrays

我的C驱动器中有一个名为new.txt的文本文件,我试图使用以下程序使用java程序将此文件的内容导入到我的多维数组中。

package square;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.nio.Buffer;
import java.util.Arrays;
import java.util.Scanner;

public class Square {

    public static void main(String[] args) {
        String a[][] = new String[4][4];
        try {
            FileReader fr = new FileReader("C://new.txt");
            Scanner scanner=new Scanner(fr);
            for (int i = 0; i < 5; i++) {
                for (int j = 0; j < i; j++) {
                    a[i][j] = scanner.next();
                }
            }
            System.out.print(Arrays.deepToString(a));
            scanner.close();
        } 

        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}

当我试图运行此程序时,我得到以下异常。

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at square.Square.main(Square.java:20)

当我将a[i][j] = scanner.next();更改为a[i][j] = scanner.nextInt();并将数组类型更改为int时,它会抛出以下异常。

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at square.Square.main(Square.java:20)

请让我知道我哪里出错了以及如何解决。

我的文字内容是。

#####
#####
#####
#####
…..

3 个答案:

答案 0 :(得分:0)

默认分隔符是空格。由于您没有任何空格,因此第一个字符串读取本身是##### \ n ##### \ n ##### \ n ### ##。但是这个问题还有很多其他问题,例如循环错误。可以尝试以下更改,看看它是否适合你。否则请提供更多解释

String a[][] = new String[5][5];
Scanner scanner=new Scanner(fr).useDelimiter("");
for (int i = 0; i < 5; i++)
   for (int j = 0; j < 5; i++) {
       if(scanner.hasNext("\n"))
           scanner.next();
       a[i][j] = scanner.next();
      }

 System.out.print(Arrays.deepToString(a));
        scanner.close();

答案 1 :(得分:0)

这里的问题很简单。首先看一下你的文本文件:

#####
#####
#####
#####
…..

这里我们有5个令牌(4 x'#####'和1 x'...... ..')。看一眼: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html在next()函数中。

NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed

因此,在扫描仪读取最后一个令牌后,即“......”,没有更多可用的令牌。

这是我建议的解决方案:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Square {

    public static void main(String[] args) {
        String a[][] = new String[5][5];
        try {
            FileReader fr = new FileReader("new.txt");
            Scanner scanner=new Scanner(fr);
            ArrayList<String> l = new ArrayList<String>();
            while(scanner.hasNext())
            {
                l.add(scanner.next());
            }
            for(int i = 0; i < l.size(); ++i)
            {
                String toSplit = l.get(i);
                String[] splitted = toSplit.split("");
                for(int j = 0; j < splitted.length; ++j)
                {
                    a[i][j] = splitted[j];
                }
            }
            scanner.close();
        } 

        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // test the result
        for(int i = 0; i < a.length; ++i)
        {
            for(int j = 0; j < a[i].length; ++j)
            {
                System.out.println(a[i][j]);
            }
        }
    }
}

注意:最后两行为空,因为最后一个标记有3个字符。 所以[4] [3]和[4] [4]将为空。

答案 2 :(得分:0)

前面的注意事项:

请检查String数组的两个维度。目前它是

new String[4][4];

并允许存储16个值(4x4)。你的循环中使用的代码看起来像你期望更多的值。因此我将数组增加到

new String[5][5];

现在回答你的问题:

要绕过外部for - 循环中的固定值5,我将其替换为while - 循环:

int i=0;
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  String[] separatedChars = line.split("(?!^)");
  for (int j = 0; j < 5; j++) {
    a[i][j] = separatedChars[j];
  }
  i++;
}
System.out.print(Arrays.deepToString(a));
scanner.close();

我没有在内部for - 循环中仅使用next,而是使用scanner.nextLine()来读取完整的行,然后将其拆分。然后使用结果填充给定的数组。 输出四行5x#

[[#, #, #, #, #], [#, #, #, #, #], [#, #, #, #, #], [#, #, #, #, #], [null, null, null, null, null]]s