2012-03-09 65 views
0

這是一個錯誤消息,隨着我嘗試在我的程序中顯示結果時不斷出現。我需要幫助瞭解錯誤消息

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 
    at AddressBookIO.getEntriesString(AddressBookIO.java:38) 
    at AddressBookEntryApp.main(AddressBookEntryApp.java:42) 

我幾乎可以肯定我的代碼是正確的。除了顯示我的結果之外,我的程序會完成它想要做的一切。 「」main「java.lang.ArrayIndexOutOfBoundsException:0」是使我困惑的部分。

繼承人爲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; 
      } 
     } 
    } 
} 
} 
+0

請發佈您的(相關)代碼。 – 2012-03-09 05:10:36

+3

「我幾乎可以肯定我的代碼是正確的」 - >它不是,因此是錯誤消息。相信你的編譯器。 – JRL 2012-03-09 05:11:45

+0

我相信它,我只是因爲它而受到傷害。 – 2012-03-09 05:26:16

回答

0

ArrayIndexOutOfBoundsException當您試圖訪問一個指數,這比指定數組的大小更被拋出。

嘗試改變這一點:

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(); 
} 
+0

非常感謝你 – 2012-03-09 05:38:31

+0

@BradWhite:你的歡迎,我很高興它確實幫助了你:-) – 2012-03-09 05:39:25

1

例外意味着你正在訪問一個數組的元素超出了數組的大小。因此,您需要提供代碼的詳細信息,以便能夠讓您知道問題的原因。

+0

+1,爲快速和正確的答覆,即使代碼已發佈之前:-) – 2012-03-09 05:29:33

1

它表示數組已經被非法索引訪問。索引或者是負數,或者大於或等於數組的大小。

根據您的錯誤日誌,在AddressBookIO.java的行號38處發生此異常。

可能是這裏..

  String name = columns[0]; 
      String emailAddress = columns[1]; 
      String phoneNumber = columns[2]; 

如果在任一0,1或2個不元件..

1

該錯誤消息是相當清楚的:第1元件的(索引0)數組與沒有元素已被錯誤地訪問。

異常在線程 「主」 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

+0

我認爲我按照你的說法,我只是沒有看到修復程序需要發生的地方 – 2012-03-09 05:20:37

+0

@BradWhite那麼,檢查列.length嘗試訪問邊界之外的東西...問題是爲什麼它不包含預期的元素? – 2012-03-09 05:23:07

+0

我明白如何跟蹤錯誤信息到代碼行。我不明白代碼有什麼問題。 AddressBookIO類是由教師提供給我們的類。 – 2012-03-09 05:28:34

1

在 'address_book.txt,' 也許是一個空行?

1

您正試圖訪問空數組的第一個元素。它不存在,所以你從運行時間得到一個異常。

您試圖訪問的數組是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);