5

テキスト ファイルの 1 行の数値を 1 行ずつ解析したいと考えています。たとえば、_ をスペースとして想像してください

私のテキストファイルの内容は次のようになります:

___34_______45
_12___1000
____4______167
...

私はあなたがアイデアを得たと思います。各行には、数字を区切るさまざまな数のスペースが含まれる場合があります。つまり、パターンはまったくありません。最も簡単な解決策は、文字ごとに読み取り、それが数値であるかどうかを確認し、数値文字列の終わりまでそのようにして解析することです。しかし、何か他の方法があるはずです。配列などの特定のデータ構造を取得できるように、Javaでこれを自動的に読み取るにはどうすればよいですか

[34,45]
[12,1000]
[4,167]
4

3 に答える 3

11

Use java.util.Scanner. It has the nextInt() method, which does exactly what you want. I think you'll have to put them into an array "by hand".

import java.util.Scanner;
public class A {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int v1 = in.nextInt(); //34
    int v2 = in.nextInt(); //45
    ...
  }
}
于 2012-09-17T02:55:49.703 に答える
4

If you only need your numbers in a data structure, e.g. a flat array, then you can read the file with a Scanner and a simple loop. Scanner uses whitespace as the default delimiter, skipping multiple whitespaces.

Given List ints:

Scanner scan = new Scanner(file); // or pass an InputStream, String
while (scan.hasNext())
{
    ints.add(scan.nextInt());
    // ...

You'll need to handle exceptions on Scanner.nextInt.

But your proposed output data structure uses multiple arrays, one per line. You can read the file using Scanner.nextLine() to get individual lines as String. Then use String.split to split around whitespaces with a regex:

Scanner scan = new Scanner(file); // or InputStream
String line;
String[] strs;    
while (scan.hasNextLine())
{
    line = scan.nextLine();

    // trim so that we get rid of leading whitespace, which will end
    //    up in strs as an empty string
    strs = line.trim().split("\\s+");

    // convert strs to ints
}

You could also use a second Scanner to tokenize each individual line in an inner loop. Scanner will discard any leading whitespace for you, so you can leave off the trim.

于 2012-09-17T02:55:47.453 に答える
1

BufferedReader文字列のsplit()機能を使って昔ながらの方法でそれをバムしてください:

BufferedReader in = null;
try {
    in = new BufferedReader(new FileReader(inputFile));
    String line;
    while ((line = in.readLine()) != null) {
        String[] inputLine = line.split("\\s+");
        // do something with your input array
    }
} catch (Exception e) {
    // error logging
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (Exception ignored) {}
    }
}

(Java 7finallyを使用している場合、try-with-resourcesを使用していれば、ブロックは不要です。)

これにより、______45___23(_は空白)のようなものが配列に変更され["45", "23"]ます。それらを整数として必要な場合は、String配列をint配列に変換する関数を作成するのは非常に簡単です。

public int[] convert(String[] s) {
    int[] out = new int[s.length];
    for (int i=0; i < out.length; i++) {
        out[i] = Integer.parseInt(s[i]);
    }
    return out;
}
于 2012-09-17T03:03:21.690 に答える