Pregunta

Aquí hay un mensaje de error que sigue surgiendo, ya que trato de resultar de disposición en mi programa.

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

Estoy casi seguro de que mi código es correcto.Mi programa hace todo lo que se supone que debe hacer, excepto mostrar mis resultados.El "" principal "java.lang.arrayindexoutofboundsexception: 0" es la parte que me confunde.

Heres el código para Directebookio.Java, y DirecciónBookEntryApp

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);
    }
  }
}

y

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;
            }
        }
    }
}
}

¿Fue útil?

Solución

ArrayIndexOutOfBoundsException se lanza cuando intenta acceder a un índice, que es más del tamaño de la matriz especificada.

Intenta cambiar esto:

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

a esto:

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

Otros consejos

La excepción significa que está accediendo a un elemento de una matriz más allá del tamaño de la matriz.Por lo tanto, debe proporcionar los detalles de su código para poder informarle la causa del problema.

Indica que se ha accedido a una matriz con un índice ilegal.El índice es negativo o mayor o igual al tamaño de la matriz.

Según sus registros de errores ... Code en la línea No: 38 en AddressBookIO.java está lanzando esta excepción.

podría estar aquí ...

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

Si no hay ningún elemento en 0, 1 o 2 ..

El mensaje de error es bastante claro: el primer elemento (índice 0) de una matriz con no se ha accedido incorrectamente.

excepción en el hilo "principal" java.lang.arrayindexoutofboundsexception: [índice es] 0

Por ejemplo, esto lanzaría esa excepción:

int bad = (new int[0])[0]; // no elements :(

Mientras que lo siguiente está bien:

int ok = (new int[1])[0];  // one element, can access it!

Sospecho que es esto:

String[] columns = line.split(FIELD_SEP); // empty array?
String name = columns[0];                 // KABOOM!

En cualquier caso, verifique el código en la línea reportada a la excepción.

en DirectBookIO.GETENTRIESTRING ( diretondio.java:38 )

¿Una línea en blanco en 'diron_dit_book.txt' tal vez?

Está intentando acceder al primer elemento de una matriz vacía.No existe, por lo que obtiene una excepción desde el tiempo de ejecución.

La matriz que está intentando acceder es el resultado del método split().Esto solo devolverá una matriz vacía si pasa una cadena de delimitadores: "\t"

Por lo tanto, debe haber algunas líneas que contengan solo las pestañas con nada entre ellos.

En lugar de usar split(), debe considerar aplicar la expresión regular a cada línea.De esta manera, puede validar el formato de la línea y Aplicar "grupos de captura" al mismo tiempo para extraer valores fácilmente para cada campo, incluso si son cadenas vacías.

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);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top