从 .txt 文件读取

Reading from a .txt file

给你一个文本文件 (customer.txt),其中存储了客户的名字、姓氏和年龄:

Ali Aslan 25 
Ayse Demir 35 
Ahmet Gemici 17 .
.
.

您应该处理此文件并找出以下每个范围内的客户数量:

0 - 19 
20 - 59 
60 -

这是我的代码:

import java.io.*;
import java.util.*;

public class ass11 {
    public static void main(String[] args) {
        Scanner inputStream = null;
        try {
            inputStream = new Scanner(new FileInputStream("customer.txt"));
        }
        catch (FileNotFoundException e) {
            System.out.println("file customer.txt not found");
            System.exit(0);
        }
        int next, x = 0, y = 0, z = 0, sum = 0;
        while(inputStream.hasNextInt()) {
            next = inputStream.nextInt();
            sum = sum + next;
            if (next >= 60)
                x++;
            else if (next >= 19 && next <= 59)
                y++;
            else
               z++;
        }
        inputStream.close();
        System.out.println(x + " customer bigger than 60");
        System.out.println(y + " customer between 19 and 59");
        System.out.println(z + " customers smaller then 19");
    }
}

它只读取数字。当我把名字和姓氏写入文本文件时,它不起作用,我没有使用 split() 方法...

我建议使用原始文件进行测试:

Ali Aslan 25 
Ayse Demir 35 
Ahmet Gemici 17

每一行都是一个名字加上年龄,所以你会得到这样的代码:

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file" ), "UTF-8"));

String line;
while ((line = reader.readLine()) != null) {
    String[] contents = line.split(" ");
    // Assume contents is 3 long: name, surname, age
    System.out.printf("%s %s is %d", contents[0], contents[1], Integer.parseInt(contents[2]));
}

是的,这确实使用了 split 方法,在我看来这更容易。您还可以使用 next()next()nextInt()

循环调用扫描仪

试试这个代码。有效。

import java.io.BufferedReader;
import java.io.FileReader;

public class MyProject {

    public static void main(String [] args){
      String path = "C:/temp/stack/scores.txt";
      processTextFile(path);    
    }

    public static void processTextFile(String filePath) {

        BufferedReader br = null;

        try {

            br = new BufferedReader(new FileReader(filePath));
            String line = br.readLine();
            String [] tokens = null;
            int score = 0;
            int x = 0;
            int y = 0;
            int z = 0;

            while (line != null) {
                tokens = line.split(" ");
                score = Integer.parseInt(tokens[tokens.length -1]);

                if(score >= 0 && score < 20){
                    x++;
                }
                if(score >= 20 && score < 60){
                    y++;
                }
                if(score > 60){
                    z++;
                }

                line = br.readLine();
            }

            if (br != null) {
                br.close();
            }

            System.out.println("0-20 = " + x + ", 20-60 = " + y + ", 60+ = " + z);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}