我真的是编程新手,如果我错过了一些简单的事情,对不起。过去几天一直在这个问题上停留。
我已经制作了一种读取文件文本的方法。 (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;
}
答案 0 :(得分:1)
也许您应该喜欢以下内容:
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;
}