首页 > 解决方案 > 从不同的方法访问数据?

问题描述

我对编程真的很陌生,如果我错过了一些完全简单的东西,我很抱歉。过去几天一直在这个问题上。

我制作了一种读取文件文本的方法。(readText) 文本文件有多行。每行都有一个具有多个分数的用户。每个名称和分数都有自己的变量分配给它们。每行重复一次。我知道文件正在被读取,就好像我以相同的方法执行 println 一样,它输出与该文件相对应的所有分数,但每行(我希望稍后解决的另一个问题)

在另一种方法(totalScore)中,我试图访问名称和分数并将它们用于一些加/减等。

对于我的一生,我只是无法从 totalScore 中的 readText 方法访问变量。

代码:

    public static boolean readText() {
    File file = new File("C:/test.txt");

    try {
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String[] words = scanner.nextLine().split(",");

            int id = Integer.parseInt(words[0]);
            String firstName = words[1];
            String lastName = words[2];
            int score1 = Integer.parseInt(words[3]);
            int score2 = Integer.parseInt(words[4]);
            int score3 = Integer.parseInt(words[5]);
            int score4 = Integer.parseInt(words[6]);

            addUser(id, firstName, lastName, score1, score2, score3,score4);

        }
        scanner.close();
    } catch (FileNotFoundException e) {
        System.out.println("Failed to read file");
    }
    return true;
}

private static void addUser(id,firstName,lastName,score1,score2,score3,score4); {
}

private static void totalScore() {

totalsc = score1+score2;
}

标签: javamethods

解决方案


也许你应该这样做:

public static boolean readText() {
    File file = new File("C:/test.txt");

    try {
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            String[] words = scanner.nextLine().split(",");

            int id = Integer.parseInt(words[0]);
            String firstName = words[1];
            String lastName = words[2];
            int score1 = Integer.parseInt(words[3]);
            int score2 = Integer.parseInt(words[4]);
            int score3 = Integer.parseInt(words[5]);
            int score4 = Integer.parseInt(words[6]);

            addUser(id, firstName, lastName, score1, score2, score3,score4);

        }
        scanner.close();
    } catch (FileNotFoundException e) {
        System.out.println("Failed to read file");
    }
    return true;
}

private static void addUser(int id, String firstName,String  lastName, int score1,int score2,int score3,int score4) {
    return;
}

private static void totalScore(int score1, int score2) {
    int totalsc = 0;
    totalsc = score1+score2;
}

推荐阅读