当我用Java中的扫描器类读取.txt文件时,我怎么才能读取字符串或整数

时间:2018-05-29 22:58:08

标签: java arrays string java.util.scanner java-io

嘿伙计这是我的第一个问题,所以如果我有任何错误或错误,我很抱歉。

所以我正在处理一件我目前仍然失败的事情,就像在标题中所说的那样,只读取.txt文件中的字符串和整数。这是我的代码:

 File file = new File("C:\\Users\\Enes\\Desktop\\test.txt");
    Scanner scn = new Scanner(file);
    String[] s = new String[10];
    int i = 0;
    int[] fruits = new int[10];

    while (scn.hasNextInt()) {

        fruits[i++] = scn.nextInt();

    }while (scn.hasNext()) {

        s[i++] = scn.next();

    }

    for (int elm : fruits) {
        System.out.print(elm + "\t");
        System.out.println("\n");
    }
    for (String ele : s) {
        System.out.print(ele + "\t");
    }

这是写在.txt文件上的内容

Apple 5
Pear 3

输出就像:

0   0   0   0   0   0   0   0   0   0   
Apple   5   Pear    3   null    null    null    null    null    null

所以我想得到Apple和Pear,不同数组中的字符串以及不同数组中的整数5和3。我怎样才能做到这一点?任何帮助都会非常感激。谢谢大家!

2 个答案:

答案 0 :(得分:2)

首先,我将您的变量重命名为有用的东西:

String[] names = new String[10];
int[] counts = new int[10];

现在,你试图抓住所有10个数字然后全部10个名字。但这不是您的数据布局方式。

我会用扫描仪抓住线,然后从那里拆分:

Scanner sc = new Scanner(new File(file));
int index = 0;
while(sc.hasNextLine()) {
    String line = sc.nextLine();
    String[] tokens = line.split(" ");
    names[index] = tokens[0];
    counts[index] = Integer.parseInt(tokens[1]);
    index++;
}

对于输出,我们同时迭代两个循环:

for(int i = 0; i < 10; i++) {
    System.out.println(names[i] + "\t" + counts[i]);
}

答案 1 :(得分:0)

这是对corsiKa答案的修改(它本身就是正确的+1),但它演示了如何使用第二个Scanner来解析line ..

int index = 0;
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    Scanner lineScanner = new Scanner(line);
    names[index] = lineScanner.next();
    counts[index] = lineScanner.nextInt();
    index++;
}

因为人们似乎忘记Scanner可以解析String