Я довольно новичок в программировании и получаю сообщение об ошибке, которое, я уверен, легко исправить для более опытных людей.
Вот что у меня есть:
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)
Прежде чем пытаться выполнить часть номера офиса, первые два (фамилия и имя) напечатаны нормально, но номер офиса, кажется, не работает.
Есть идеи?
Редактировать: Спасибо за все сообщения, ребята, я все еще не могу понять это, хотя.Может кто-нибудь опубликовать что-то действительно тупое?Я уже час пытаюсь это исправить и не могу получить.