简体   繁体   中英

Java: reading numbers from a .txt file

I'm trying to read a.txt file of the of the form:

Last game points:

level 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:

    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. 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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