【发布时间】:2014-11-20 17:42:54
【问题描述】:
我正在尝试使用 split() 方法将字符串和整数从数组中分离出来,但无法正常工作。
我在第 7 行得到了 Index Of Bounds Exception,它是 surname = list[1];,但不知道为什么?
我最终要做的是拆分每个元素并获取整数的平均值,因此文件中的第一行文本将显示为 Mildred Bush 45 65 45 67 65 和我写入的新文本行新文件将显示为 Bush,Mildred:最终得分为 x.xx。
我已经尝试了很长时间,但就是无法正常工作。
我的代码:
public static void splitTest()
{
String forename, surname, tempStr, InputFileName, OutputFileName, nextLine;
int sum = 0;
float average;
//forename = "Mildred";
//surname = "Bush";
nextLine = "";
tempStr = "";
String[] list = tempStr.split(" ");
String[] list = new String[12];
forename = list[0];
surname = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
FileReader fileReader = null;
BufferedReader bufferedReader = null;
FileOutputStream outputStream = null;
PrintWriter printWriter = null;
clrscr();
// Prompt user for input filename
System.out.println("Please enter the name of the file that is to be READ (e.g. details.txt) : ");
InputFileName = Genio.getString();
// Prompt user for output filename
System.out.println("Please enter the name of the file that is to be WRITTEN TO (e.g. newDetails.txt) : ");
OutputFileName = Genio.getString();
try {
// Open input file
fileReader = new FileReader(InputFileName);
bufferedReader = new BufferedReader(fileReader);
// Open output file
outputStream = new FileOutputStream(OutputFileName);
printWriter = new PrintWriter(outputStream);
// Read a line
tempStr = bufferedReader.readLine();
// While there are lines in the input file
while (tempStr != null) {
String[] list;
list = tempStr.split(" ");
surname = list[0];
forename = list[1];
int[] scores = new int[5];
scores[0] = Integer.parseInt(list[2]);
scores[1] = Integer.parseInt(list[3]);
scores[2] = Integer.parseInt(list[4]);
scores[3] = Integer.parseInt(list[5]);
scores[4] = Integer.parseInt(list[6]);
for(int i=0; i < scores.length; i++){
sum = sum + scores[i];
average = (float)sum/scores.length;
// Print it to screen
System.out.println(tempStr);
// Write it to the output file + a new-line
printWriter.write(tempStr +"\n");
// Read a line
tempStr = bufferedReader.readLine();
System.out.println("\n\nYOUR NEW FILE DATA IS DISPLAYED ABOVE!\n\n");
pressKey();
// Close the input file
bufferedReader.close();
// Close the output file
printWriter.close();
}
}
上面写着Genio,这是一个处理用户输入的类。谢谢!
【问题讨论】: