나를 이해하는 데 도움이 필요한 오류 메시지
-
09-12-2019 - |
문제
여기에 오류 메시지가 오로라도 disply 결과에 내 프로그램입니다.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at AddressBookIO.getEntriesString(AddressBookIO.java:38)
at AddressBookEntryApp.main(AddressBookEntryApp.java:42)
나는 거의 확실 내 코드는 올바른 것입니다.내 프로그램은 모두 그것은 가정을 제외하고 전시 결과입니다.는""main"java.랭.ArrayIndexOutOfBoundsException:0"이 부분을 혼동하는 나입니다.
Heres 코드 AddressBookIO.java 고 AddressBookEntryApp
import java.io.*;
public class AddressBookIO
{
private static File addressBookFile = new File("address_book.txt");
private static final String FIELD_SEP = "\t";
private static final int COL_WIDTH = 20;
// use this method to return a string that displays
// all entries in the address_book.txt file
public static String getEntriesString()
{
BufferedReader in = null;
try
{
checkFile();
in = new BufferedReader(
new FileReader(addressBookFile));
// define the string and set a header
String entriesString = "";
entriesString = padWithSpaces("Name", COL_WIDTH)
+ padWithSpaces("Email", COL_WIDTH)
+ padWithSpaces("Phone", COL_WIDTH)
+ "\n";
entriesString += padWithSpaces("------------------", COL_WIDTH)
+ padWithSpaces("------------------", COL_WIDTH)
+ padWithSpaces("------------------", COL_WIDTH)
+ "\n";
// append each line in the file to the entriesString
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String name = columns[0];
String emailAddress = columns[1];
String phoneNumber = columns[2];
entriesString +=
padWithSpaces(name, COL_WIDTH) +
padWithSpaces(emailAddress, COL_WIDTH) +
padWithSpaces(phoneNumber, COL_WIDTH) +
"\n";
line = in.readLine();
}
return entriesString;
}
catch(IOException ioe)
{
ioe.printStackTrace();
return null;
}
finally
{
close(in);
}
}
// use this method to append an address book entry
// to the end of the address_book.txt file
public static boolean saveEntry(AddressBookEntry entry)
{
PrintWriter out = null;
try
{
checkFile();
// open output stream for appending
out = new PrintWriter(
new BufferedWriter(
new FileWriter(addressBookFile, true)));
// write all entry to the end of the file
out.print(entry.getName() + FIELD_SEP);
out.print(entry.getEmailAddress() + FIELD_SEP);
out.print(entry.getPhoneNumber() + FIELD_SEP);
out.println();
}
catch(IOException ioe)
{
ioe.printStackTrace();
return false;
}
finally
{
close(out);
}
return true;
}
// a private method that creates a blank file if the file doesn't already exist
private static void checkFile() throws IOException
{
// if the file doesn't exist, create it
if (!addressBookFile.exists())
addressBookFile.createNewFile();
}
// a private method that closes the I/O stream
private static void close(Closeable stream)
{
try
{
if (stream != null)
stream.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
// a private method that is used to set the width of a column
private static String padWithSpaces(String s, int length)
{
if (s.length() < length)
{
StringBuilder sb = new StringBuilder(s);
while(sb.length() < length)
{
sb.append(" ");
}
return sb.toString();
}
else
{
return s.substring(0, length);
}
}
}
고
import java.util.Scanner;
public class AddressBookEntryApp
{
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Address Book application");
System.out.println();
Scanner sc = new Scanner(System.in);
int menuNumber = 0;
while (menuNumber != 3)
{
// display menu
System.out.println("1 - List entries");
System.out.println("2 - Add entry");
System.out.println("3 - Exit\n");
// get input from user
menuNumber = Validator.getIntWithinRange(sc, "Enter menu number: ", 0, 4);
System.out.println();
switch (menuNumber)
{
case 1:
{
String entriesString = AddressBookIO.getEntriesString();
System.out.println(entriesString);
break;
}
case 2:
{
// get data from user
String name = Validator.getRequiredString(sc, "Enter name: ");
String emailAddress = Validator.getRequiredString(sc, "Enter email address: ");
String phoneNumber = Validator.getRequiredString(sc, "Enter phone number: ");
// create AddressBookEntry object and fill with data
AddressBookEntry entry = new AddressBookEntry();
entry.setName(name);
entry.setEmailAddress(emailAddress);
entry.setPhoneNumber(phoneNumber);
AddressBookIO.saveEntry(entry);
System.out.println();
System.out.println("This entry has been saved.\n");
break;
}
case 3:
{
System.out.println("Goodbye.\n");
break;
}
}
}
}
}
해결책
ArrayIndexOutOfBoundsException
throw 에 액세스하려고 할 때 인덱스보다 더 크기를 지정한 배열입니다.
려고 이를 변경하려면:
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String name = columns[0];
String emailAddress = columns[1];
String phoneNumber = columns[2];
entriesString += padWithSpaces(name, COL_WIDTH) +
padWithSpaces(emailAddress, COL_WIDTH) +
padWithSpaces(phoneNumber, COL_WIDTH) +
"\n";
line = in.readLine();
}
다.
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
if (columns.length > 2)
{
String name = columns[0];
String emailAddress = columns[1];
String phoneNumber = columns[2];
entriesString += padWithSpaces(name, COL_WIDTH) +
padWithSpaces(emailAddress, COL_WIDTH) +
padWithSpaces(phoneNumber, COL_WIDTH) +
"\n";
}
line = in.readLine();
}
다른 팁
예외는 배열의 크기를 초과하여 배열의 요소에 액세스하는 것을 의미합니다.따라서 문제의 원인을 알려줄 수있는 코드의 세부 정보를 제공해야합니다.
어레이가 불법적 인 색인으로 액세스되었음을 나타냅니다.인덱스는 어레이의 크기보다 부정적이거나 크거나 같습니다.
오류 로그에 따라. LINE NO : 38에서 AddressBookIO.java
에서이 예외가 던져집니다.
여기있을 수 있습니다 ..
String name = columns[0];
String emailAddress = columns[1];
String phoneNumber = columns[2];
.
0, 1 또는 2에서 요소가없는 경우 ..
오류 메시지가 꽤 명확합니다. 요소가없는 배열의 첫 번째 요소 (인덱스 0) 이 잘못 액세스되었습니다.
스레드 "main" java.lang.ArrayIndexoutOfBoundsException : [색인은] 0
예를 들어,이 예외가 발생합니다.
.int bad = (new int[0])[0]; // no elements :(
다음은 괜찮습니다 :
.int ok = (new int[1])[0]; // one element, can access it!
나는 그것이 이것이라도 의심된다 :
.String[] columns = line.split(FIELD_SEP); // empty array? String name = columns[0]; // KABOOM!
어떤 경우에도 예외에서 보고 된 라인의 코드를 확인하십시오.
addressbookio.getEntriesstring ( addressbookio.java:38 / strong>)
'address_book.txt'의 빈 줄?
빈 배열의 첫 번째 요소에 액세스하려고합니다.그것은 존재하지 않으므로 런타임에서 예외가 발생합니다.
액세스하려는 어레이는 split()
메소드의 결과입니다.구분 기호 문자열을 전달하면 빈 배열 만 반환합니다. "\t"
그래서, 그 사이에 아무 것도없는 탭이있는 탭 만 포함되어야합니다.
split()
를 사용하는 대신 각 행에 정규 표현식을 적용하는 것을 고려해야합니다.이렇게하면 및 라인의 형식을 동시에 유효성을 검증하여 각 필드에 값을 쉽게 추출 할 수 있습니다.
.Pattern p = Pattern.compile("([^\t]*)\t([^\t]*)\t([^\t]*)");
...
Matcher m = p.matcher(line);
if (!m.matches()) {
/* The line is invalid; skip it or throw an exception. */
...
}
String name = m.group(1);
String emailAddress = m.group(2);
String phoneNumber = m.group(3);