繁体   English   中英

从不同的方法访问数据?

[英]Accessing data from different methods?

我真的是编程新手,如果我错过了一些简单的事情,对不起。 过去几天一直在这个问题上困扰。

我已经制作了一种读取文件文本的方法。 (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;
}

也许您应该喜欢以下情况:

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

暂无
暂无

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

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