所以我一直致力于从列表中读取数组并使用内容进行计算。
我有数组部分=
[Mildred, Bush, 45, 65, 45, 67, 65, Fred, Snooks, 23, 43, 54, 23, 76, Morvern, Callar, 65, 45, 34, 87, 76, Colin, Powell, 34, 54, 99, 67, 87, Tony, Blair, 67, 76, 54, 22, 12, Peter, Gregor, 99, 99, 99, 99, 99]
这里假设每7个值是文本文件的一行。所以我想要做的是取名字,将数字改成整数,然后进行计算然后输出它们。
我尝试使用的代码是:
for(int i=0; i < 42;i=i+7) {
float avg;
float total;
for (int x=2; x < 7;x++) {
String number = parts[x];
int num = Integer.parseInt(number);
total = total + num;
}
avg = total/6;
System.out.print(parts[i+1] + "," + parts[i+2] + + "Final Score is avg");
}
但是我遇到了错误
The type of the expression must be an array type but it resolved to List<String>
所以我想知道如何解决这个问题
更新了试用:
String fileName =&#34; Details.txt&#34 ;;
String wfilename = "output.txt";
// This will reference one line at a time
String line = null;
String temp;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
FileWriter fileWriter = new FileWriter(wfilename);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> parts = new ArrayList<>();
String [] temp2;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
temp = line;
temp2 = line.split(" ");
for(int i=0; i<7; i++){
parts.add(temp2[i]);
}
//System.out.println(line);
bufferedWriter.write(line + "\n");
}
System.out.print(parts);
//conver to an array of strings
String[] partsArray = parts.toArray();
//code to do take values from array, do calculations and format to output
for(int i=0; i < 42;i=i+7) {
float avg;
float total = 0;
for (int x=2; x < 7;x++) {
String number = partsArray[x];
int num = Integer.parseInt(number);
total = total + num;
}
avg = total/6;
System.out.print(partsArray[i+1] + "," + partsArray[i+2] + "Final Score is" + avg);
}
// Always close files.
bufferedReader.close();
bufferedWriter.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
答案 0 :(得分:3)
你明确有一份清单。你可以把它变成一个数组,就像这个
String[] partsArray = parts.toArray(new String[parts.size()]);
或开始像列表一样访问它,如此
String number = parts.get(x);
答案 1 :(得分:-1)