我很新的編程,我得到一個錯誤,我敢肯定,這是一個容易修復的更有經驗的人。新手程序員需要建議:「字符串索引超出範圍」 - Java
以下是我有:
import java.io.*;
import java.util.Scanner;
public class ReadNamesFile
{
public static void main(String[] args) throws IOException {
// make the names.csv comma-separated-values file available for reading
FileReader f = new FileReader("names.csv");
BufferedReader r = new BufferedReader(f);
//
String lastName="unknown", firstName="unknown", office="unknown";
// get first line
String line = r.readLine();
// process lines until end-of-file occurs
while (line != null)
{
// get the last name on the line
//
// position of first comma
int positionOfComma = line.indexOf(",");
// extract the last name as a substring
lastName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the first name as a substring
firstName = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+1);
// extract the office number as a substring
office = line.substring(0,positionOfComma);
// truncate the line removing the name and comma
line = line.substring(positionOfComma+2);
//
//
//
// display the information about each person
System.out.print("\nlast name = "+lastName);
System.out.print("\t first name = "+firstName);
System.out.print("\t office = "+office);
System.out.println();
//
// get the next line
line = r.readLine();
}
}
}
基本上,它找到的姓氏,名字和辦公室電話號碼在.csv文件中,並打印出來。
當我編譯我沒有得到任何錯誤,但是當我運行它,我得到:
java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1955)
at ReadNamesFile.main(ReadNamesFile.java:34)
之前要做的辦公室號碼部分,前兩個(姓和名)打印出來罰款但辦公室號碼似乎不起作用。
任何想法?
編輯:感謝所有職位的人,我仍然無法真正弄清楚。有人可以發佈一些真正愚蠢的東西嗎?我一直試圖解決這個問題一個小時,我無法得到它。
這將有助於注意哪一行是第34行。 –
建議:1)閱讀錯誤消息。喜歡錯誤信息。它從何而來?這是什麼意思? 2)使用調試器並停止異常;現在的價值是什麼讓它爆炸?他們爲什麼如此而不是「有效」的價值? – 2011-10-07 03:17:50