1

假设我有一个这样的文本文件。

1 4 6
2 3    
5 8 9 4
2 1
1

我想要做的是将它们存储到一个二维数组中,它们是如何表示的。经过一番谷歌搜索和阅读后,我想出了以下代码。

Scanner s = new Scanner(new BufferedReader(new FileReader("myData.txt")));     

while (s.hasNextLine())
{
    String myStr = s.nextLine();
    x = 0;
    for ( int y = 0; y <= myStr.length(); y+=2)
    {
        myStr = myStr.trim();
        tempStr = myStr.substring(y, y+1)
        num[row][coln] = Integer.parseInt(tempStr);
        coln++
    }
    row++;
}

它工作正常,但对于只有 1 位数字的整数。但是,如果我有不同长度的整数怎么办。我怎样才能动态检查整数的长度?

例如,我想将此文本文件存储在二维数组中

13 4 652
2 343    
5 86 9 41
2 18
19

如果有人能指出我正确的方向,那将非常有帮助。谢谢

4

7 回答 7

3

您可以split()用于字符串。如果您使用空格作为分隔符,它将返回一个字符串数组,其中行中的每个数字将映射到数组中的一个槽。然后,遍历数组并使用Integer.parseInt().

另一种方法是将输出从nextLine()另一个输入Scanner并用于nextInt()检索数字。

于 2013-10-27T04:47:13.033 回答
0

也许我误解了这个问题,但你为什么不这样读呢?

list1 = [map(int,x.strip().split()) for x in open("/ragged.txt")]

for z in list1:
    for y in z:
        print y,
    print

它打印以下整数(与文件内容相同):

1 4 6
2 3
5 8 9 4
2 1
1

它也适用于更长的整数。

于 2014-11-03T05:42:59.633 回答
0

使用 aMappedByteBuffer并将其作为二进制读取并以这种方式处理数字要快得多。在我在这种类似情况下的实验中,它的速度是原来的三倍。逐行阅读有两个方面的巨大开销:

  1. 垃圾收集器发疯了,因为您正在创建和丢弃如此多的String对象。
  2. 您处理每个字符两次:构造 时String一次,然后将其转换为数字时再一次。如果您拆分String然后转换每个字符,您将处理每个字符 3 次。

这取决于您是想要速度还是简洁明了的代码。毫无疑问,这种String方法更容易理解,所以最好知道文件总是很小;但如果它可能变得很大,你真的应该看看二进制方法。

于 2014-09-12T18:19:54.463 回答
0

您可以使用以下代码:

Scanner scan = new Scanner(new File("test.txt"));
scan.useDelimiter("\\Z");
String content = scan.next();
ArrayList output=new ArrayList();
ArrayList<Inteher> inner=new ArrayList<Integer>();
String[] a1=content.split("\n");
for(String a:a1){
String a2=a1.plit(" ");
for(String b:a2){
inner=new ArrayList<Integer>();
inner.add(Integer.parseInt(b));
}
output.add(inner);

}
于 2013-10-27T04:49:35.957 回答
0

我会这样做

    String[] a = mystr.split(" +");
    num[i] = new int[a.length];
    for (int j = 0; j < a.length; j++) {
        num[i][j] = Integer.parseInt(a[j]);
    }

我还会将第一部分更改如下

    List<String> lines = Files.readAllLines(Paths.get("myData.txt"), StandardCharsets.UTF_8);
    int[][] num = new int[lines.size()][];
    for(int i = 0; i < lines.size(); i++) {
        ...
于 2013-10-27T04:51:37.833 回答
0

你可以试试这个:

try {

        InputStream in = getClass().getResourceAsStream(s);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        int[][] values = new int[numRows][numCols];

        int numRows = br.readLine();
        int numCols = br.readLine();

        String delims = "\\s+";
        for (int row = 0; row < numRows; row++) {
            String line = br.readLine();
            String[] tokens = line.split(delims);
            for (int col = 0; col < numCols; col++) {
                values[row][col] = Integer.parseInt(tokens[col]);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

对于文本文件,设置如下:

10 // amount of numbers across
7 // amount of numbers down
6 6 6 6 6 65 6 6 6 6
6 6 7 6 6 6 6 6 6 6
6 6 6 6 6 6 6 6 6 6
6 6 6 6 6 6 72 6 6 6
6 6 6 6 6 6 6 6 6 6
6 6 89 6 6 6 6 345 6 6
6 6 6 6 6 6 6 6 6 6

您输入了对数和向下数,因此当它将整数读入二维数组时,它知道宽度和高度。

希望这有帮助!

于 2013-10-27T04:51:54.477 回答
0

您可以使用扫描仪类的 nextInt 方法,它会一一为您提供整数值。

首先你应该使用hasextXXX方法来检查你的文件中是否有任何整数值,比如

scanner.hasNextInt()

比你可以写一个程序

import java.util.*;

public class ScannerDemo {
   public static void main(String[] args) {

     Scanner scanner = new Scanner(new BufferedReader(new FileReader("myData.txt")));     


      while (scanner.hasNext()) {
         if (scanner.hasNextInt()) {
            System.out.println("integer present" + scanner.nextInt());
         }
         System.out.println("no integer" + scanner.next());
      }
      scanner.close();
   }

}

在 JavaDocs 中, nextInt() 方法将在以下条件下抛出这些异常:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
于 2013-10-27T04:46:34.220 回答