java - 从不同的方法访问数据?
问题描述
我对编程真的很陌生,如果我错过了一些完全简单的东西,我很抱歉。过去几天一直在这个问题上。
我制作了一种读取文件文本的方法。(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;
}
推荐阅读
- powershell - 通过网络媒体设备播放音频
- performance - 性能取决于索引类型
- c# - string.IndexOf 在 .NET 5.0 中返回不同的值
- python - Python中的跨进程内存文件系统
- java - 尝试加载 facebook 原生广告时,我的 android 应用程序崩溃 (java.lang.NoSuchMethodError: No static method isChildDirected())
- laravel - Laradock 404 Not Found Files with Symlink to Storage
- postgresql - 如何在 Windows 10 环境中使用 Docker 连接到 dbeaver?
- python - 如何从大型numpy数组中提取样本
- python - ImportError:无法从“django.db.models.fields”导入名称“字段”
- android - Amplify Hosted Web-UI 登录/注册调用随机抛出错误