0

私は先週、このばかげたコードを機能させる方法を見つけようとしました。テキストファイルからの読み取りを除いて、すべてを機能させることができました。行の個々の整数を読み取ることができますが、スペースで区切られた複数の整数を含む行が指定されると、異常になります。今、私はそれを修正しようとしましたが、コードはもうコンパイルさえしません。1行だけが問題を引き起こしています。私はコーディングが苦手なので、どこから始めればよいかわかりません。はい、私はこれをオンラインで調べました。はい、フォーラムを確認しました。はい、これを機能させるために複数の異なる方法を試しました....どうすれば修正できますか?? :(

ArrayList<Integer> list = new ArrayList<Integer>();
// the above line is in a different method in the same class, but it's relevant here


File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
    BufferedReader reader = null;

    try
    {
        reader = new BufferedReader(new FileReader(file));
        String text = null;


        while ((text = reader.readLine()) != null)
        {
            // I want the following line to read "218 150 500 330", and to store each individual integer into the list. I don't know why it won't work :(
            list.add(Integer.parseInt(src.next().trim()));
        }
    } 
    catch (FileNotFoundException e)
    {
    e.printStackTrace();
    } 
    catch (IOException e) 
    {
    e.printStackTrace();
    } 
    try
    {
   reader.close();
    }
    catch (IOException e) 
    {
    e.printStackTrace();
    }


//print out the list
System.out.println(list);

お手伝いありがとう!本当に単純なものが欠けていると確信しています...

4

3 に答える 3

1

あなたはScanner(String)好きなものを使うことができます

while ((text = reader.readLine()) != null) {
    Scanner scanner = new Scanner(text);
    while (scanner.hasNextInt()) {
        list.add(scanner.nextInt());
    }
}

もちろん、try-with-resourcesStatementと anddiamond operatorを使用することで、メソッド全体を単純化できScanner(File)ます。

public static void main(String[] args) {
    File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");

    List<Integer> list = new ArrayList<>();
    try (Scanner scanner = new Scanner(file);) {
        while (scanner.hasNextInt()) {
            list.add(scanner.nextInt());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // print out the list
    System.out.println(list);
}
于 2014-10-26T03:52:25.697 に答える
0

whileループ内でこれを行う

String[] individualArray = text.split(" ");//note space
for(String individual:individualArray){
    yourList.add(individual);//You need to parse it to integer here as you have already done
}

上記のコードでは、individualArrayには、 である個々の整数が含まれますseparated by spaceforループ内では、各文字列を整数に解析してからリストに追加する必要があります

于 2014-10-26T03:47:15.570 に答える