我正在嘗試使用split()
方法將字符串和整數與數組分開,但無法使其工作。在數組中使用split()單獨的字符串和Ints
我在第7行得到Index Of Bound異常,它說的surname = list[1];
,不知道爲什麼?
我試圖最終做的是拆分每個元素並獲得整數的平均值,以便文件中的第一行文本將讀取Mildred Bush 45 65 45 67 65和我寫入的新文本行一個新的文件會讀取布什,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
,這與用戶輸入涉及一類。謝謝!
將無法正常工作一個空的字符串。所以如果它被一個空格分開,結果數組的長度只有1. – 2014-11-20 17:47:27
@ La-comadreja我認爲這只是描述問題實際上並非如此。 – StackFlowed 2014-11-20 17:48:44
我試過,但我仍然收到錯誤。另一件事,我解析整數,應該是在開始還是在while循環? – DarkBlueMullet 2014-11-20 17:49:27