Java 将整数添加到arraylist“;分数“;
我有一个文本文件,大约有5000个名字,每个名字用一行隔开 我已经完成将所有名称添加到ArrayList“names”中,但是 我无法为我的arrayList分数添加任何内容 我不知道我哪里出错了,尤其是在addScores方法中,没有任何输出 如果需要更多信息,请询问 谢谢你的帮助Java 将整数添加到arraylist“;分数“;,java,Java,我有一个文本文件,大约有5000个名字,每个名字用一行隔开 我已经完成将所有名称添加到ArrayList“names”中,但是 我无法为我的arrayList分数添加任何内容 我不知道我哪里出错了,尤其是在addScores方法中,没有任何输出 如果需要更多信息,请询问 谢谢你的帮助 import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class ScoringNames {
BufferedReader x = null;
String location = "xxxxx\\names.txt";
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> scores = new ArrayList<Integer>();
public void readFile(){ //Opens file, and prints every line.
try{
x = new BufferedReader(new FileReader(location));
} catch(FileNotFoundException e) {
e.printStackTrace();
}
try{
String name = x.readLine();
while(name != null){
//System.out.println(name);
names.add(name);
name = x.readLine();
}
} catch(IOException e) {
e.printStackTrace();
}
}
public int nameScore(String name){
this.readFile(); //Open file and read, so that values are added to <names>
this.sortNames();
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName){
score += alphValue(i);
}
return score;
}
public void addScores(){
for(String x : names){
scores.add(nameScore(x));
}
}
public void printScores(){
for(int counter: scores)
System.out.println(counter);
}
public static void main(String[] args) {
ScoringNames abc = new ScoringNames();
abc.readFile();
abc.addScores();
abc.printScores();
}
}
从
addScores()
方法的For
循环访问时,您正在修改列表
名称
调用nameScore(String str)
方法时,不需要再次读取文件,因为所有数据都已读取并存储在names
列表中。您只需对字符串进行评估
,然后返回分数
public int nameScore(String name){
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName){
score += alphValue(i);
}
return score;
}
更改方法
nameScore
-删除两个顶部行
this.readFile(); // Open file and read, so that values are added to
// <names>
this.sortNames();
你能删除所有不相关的代码吗?你说“我不能给我的arrayList分数添加任何东西”是什么意思?您是否收到错误,或者列表是否保持为空?您收到的错误是什么?或者也是
x-'A'+1
。在addScores方法中,您为列表名称中的每个字符串调用nameScore方法。但是在nameScore方法中,您再次调用readFile,这将再次将所有名称添加到名称列表中。因此,对于每一个你试图获得分数的名字,你再次将所有名字添加到你的名字列表中。除非我弄错了,否则这应该完全爆炸。我在哪里可以添加这两个呢?您不需要添加它们,因为您已经在主函数中执行了这两个。实际上多次调用这两个函数可能会给列表
带来问题,因为每次调用时它都会不断地添加File的值。因此,您的列表中有重复的数据,这可能会给您带来问题。当我可以返回计算机时,将检查全部功能。谢谢
this.readFile(); // Open file and read, so that values are added to
// <names>
this.sortNames();
public int nameScore(String name) {
int score = 0;
char[] tempName = name.toCharArray();
for (char i : tempName) {
score += alphValue(i);
}
return score;
}