-2

我有一个文本文件,其中包含:

“我有 3 个苹果和 1 个香蕉。
所有人至少有 4 辆汽车。”

我想读取这个 .txt 文件并从中获取整数。我将在 arrayList 中存储整数变量。

public class dedede {
    public static void al() throws Exception {

        File f = new File("C:\\users\\sony\\Desktop\\456.txt");

        try {
            FileReader islem = new FileReader(f);

            char data[] = new char[(int) f.length()];

            islem.read(data);
            String metin = new String(data);

            ArrayList<Integer> yapi = new<Integer> ArrayList();

            StringTokenizer s = new StringTokenizer(metin);

            String dizi[] = new String[s.countTokens()];

            int i = 0;
            while (s.hasMoreTokens()) {
                dizi[i] = s.nextToken();
                i++;
            }

            for (int c = 0; c < dizi.length; c++) {
                if (Integer.parseInt(dizi[c]) > 0) {
                    yapi.add(Integer.parseInt(dizi[c]));
                }

            }

            System.out.println(yapi);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        al();
    }
}
4

1 回答 1

2

尝试这个:

static ArrayList<Integer> al = new ArrayList<Integer>();

public static void main(String[] args) {

    try {
        File file = new File("C:\\users\\sony\\Desktop\\456.txt");
        BufferedReader in = new BufferedReader(new FileReader(file));
        String s; 
        while ((s = in.readLine()) != null) {
            findInteger(s);
        }
        in.close();
    } catch (IOException e) {
        System.out.println("File Read Error: " + e.getMessage());
    }
    System.out.println("Integers: " + al);
}

private static void findInteger(String s){
    String [] parts = s.split(" ");

    for (int i = 0; i < parts.length; i++) {
        try{
            int j = Integer.parseInt(parts[i]);
            al.add(j);
        } catch (Exception e){}
    }
}
于 2013-05-14T17:42:31.740 回答