简体   繁体   English

Java:从 .txt 文件中读取数字

[英]Java: reading numbers from a .txt file

I'm trying to read a.txt file of the of the form:我正在尝试读取以下形式的 a.txt 文件:

Last game points:上场比赛积分:

level 1º: 200级别 1º:200

Did you do well?你做得好吗? :) :)

My goal is to read the points.我的目标是阅读要点。 In this example, it's 200. Here's what I've tried:在这个例子中,它是 200。这是我尝试过的:

    public int[] points() throws FileNotFoundException {
    int[] points = new int[StaticUtils.LEVELS.size()];
    int next = 0;
    File file = new File("Points.txt");
    Scanner scanner = new Scanner(file);
    while(scanner.hasNextInt())
        points[next++] = scanner.nextInt();
    scanner.close();
    return points;

But this results in points being just zeros.但这导致点只是零。 That is, it's reading nothing from the file... How may I fix it?也就是说,它没有从文件中读取任何内容......我该如何解决它?

I think you should format the txt more readable.我认为您应该格式化 txt 更具可读性。 Ex: level:point例如:级别:点

1:200
2:150

And you can read the string and parse it你可以读取字符串并解析它

while (scanner.hasNext()) {
        String s = scanner.nextLine();
        String[] arr = s.split(":");
        int level = Integer.parseInt(arr[0]);
        int point = Integer.parseInt(arr[1]);
        points[level] = point;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM