首页 > 解决方案 > 当我用 Java 中的 Scanner 类读取 .txt 文件时,如何只读取字符串或整数

问题描述

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

所以我正在做一件我目前一直失败的事情,那就是,正如它在标题中所说,只从 .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,它们是不同数组中的整数。我怎样才能做到这一点?任何帮助将不胜感激。谢谢大家!

标签: javaarraysstringjava.util.scannerjava-io

解决方案


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

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]);
}

推荐阅读