java - Java中的数组增广问题

标签 java arrays outofrangeexception

我这里有一个程序,应该以长度为 1 的数组开始,允许用户在数组中输入一个条目,然后用户输入的每个条目将数组的大小加倍,以避免 java.lang.ArrayIndexOutOfBoundsException 错误。按照下面代码的编写方式,计算机在第二次用户输入后会跳过else if,直接输入对不起,数据库已满。如果我在第一个 else if block 中添加 newRecords = reports,则会收到 java.lang.ArrayIndexOutOfBoundsException 错误。

public class PhoneDirectory5 {
    public static void main(String args[]) {
        **PhoneRecord[] records= new PhoneRecord[1];
        int numRecords = 0;**

        // Display list of commands
        System.out.println("Phone directory commands: \n" +
                " a - Add a new phone number\n" +
                " f - Find a new phone number\n" +
                " q - Quit\n" +
                " d - Delete record\n");

        // Read and execute commands
        while (true) {

            // Prompt user to enter a command
            SimpleIO.prompt("Enter command (a, f, d, or q): ");
            String command = SimpleIO.readLine().trim();

            // Determine whether command is "a", "f", "q", or
            // illegal. Execute command if illegal.
            **if (command.equalsIgnoreCase("a"))** {

                // Command is "a". prompt user for name and number,
                // then create a phone record and store it in the
                // database.
                **if (numRecords < records.length) {
                    SimpleIO.prompt("Enter a new name: ");
                    String name = SimpleIO.readLine().trim();
                    SimpleIO.prompt("Enter new phone number: ");
                    String number = SimpleIO.readLine().trim();
                    records[numRecords] =
                            new PhoneRecord(name, number);
                    numRecords++;
                } else if (numRecords == records.length) {
                    PhoneRecord[] newRecords = new PhoneRecord[records.length*2];
                    System.arraycopy(records, 0, newRecords, 0, records.length);
                    SimpleIO.prompt("Enter a new name: ");
                    String name = SimpleIO.readLine().trim();
                    SimpleIO.prompt("Enter new phone number: ");
                    String number = SimpleIO.readLine().trim();
                    newRecords[numRecords] =
                            new PhoneRecord(name, number);
                    numRecords++;**
                } else
                    System.out.println("Sorry, database is full.");

            } else if (command.equalsIgnoreCase("f")) {

                // Command is "f". Prompt user for search key.
                // Search the database for records whose name begins
                // with the search key. Print these names and the
                // corresponding phone numbers.
                SimpleIO.prompt("Enter name to look up: ");
                String key = SimpleIO.readLine().trim().toLowerCase();
                for (int i = 0; i < numRecords; i++) {
                    String name = records[i].getName().toLowerCase();
                    if (name.startsWith(key)) {
                        System.out.println(records[i].getName() + " " +
                                records[i].getNumber());
                        break;
                    } else if (i == numRecords - 1)
                        System.out.println("Sorry, your search did not" +
                                " match any records.");
                }
            } else if (command.equalsIgnoreCase("d")) {
                SimpleIO.prompt("Enter the name of the record to delete: ");
                String key = SimpleIO.readLine().trim().toLowerCase();
                for (int i = 0; i < numRecords; i++) {
                    String name = records[i].getName().toLowerCase();
                    if (name.startsWith(key)) {
                        records[i] = new PhoneRecord("", "");
                        break;
                    } else if (i == numRecords - 1)
                        System.out.println("Sorry, your search did not match" +
                                " any records.");
                }

            } else if (command.equalsIgnoreCase("q")) {
                // Command is "q".. Terminate program
                System.out.println("You have elected to exit the phone directory.");
                return;

            } else {
                // Command is illegal. Display error message.
                System.out.println("Command was not recognized; " +
                        "please enter only a, f, d or q.");
            }
            System.out.println();
        }
    }
}

// Represents a record containing a name and a phone number
class PhoneRecord {
    private String name;
    private String number;

    // Constructor
    public PhoneRecord(String personName, String phoneNumber) {
        name = personName;
        number = phoneNumber;
    }

    // Returns the name stored in the record
    public String getName() {
        return name;
    }

    // Returns the phone number stored in the record
    public String getNumber() {
        return number;
    }
}

话虽这么说,当我以这种方式分配新的数组空间时......

else if (numRecords == records.length) {
                    PhoneRecord[] newRecords = new PhoneRecord[records.length*2];
                    for (int i = 0; i < records.length; i++)
                        newRecords[i] = records[i];
                    records = newRecords;
                    SimpleIO.prompt("Enter a new name: ");
                    String name = SimpleIO.readLine().trim();
                    SimpleIO.prompt("Enter new phone number: ");
                    String number = SimpleIO.readLine().trim();
                    newRecords[numRecords] =
                            new PhoneRecord(name, number);
                    numRecords++;

...该程序完全按照我的需要执行,即每次用户输入时将数组大小加倍,并且从不打印“抱歉,但数据库已满”消息。我的问题是,为什么我不能让程序使用 .arraycopy 方法?任何帮助将不胜感激。

当我这样做时...

else if (numRecords == records.length) {
                    PhoneRecord[] newRecords = new PhoneRecord[records.length*2];
                    System.arraycopy(records, 0, newRecords, 0, records.length);
                    **newRecords = records;**
                    SimpleIO.prompt("Enter a new name: ");
                    String name = SimpleIO.readLine().trim();
                    SimpleIO.prompt("Enter new phone number: ");
                    String number = SimpleIO.readLine().trim();
                    newRecords[numRecords] =
                            new PhoneRecord(name, number);
                    numRecords++;

...是当我收到 arrayindexoutofbounds 错误时。

最佳答案

Java 中数组的长度是固定的。如果您想要一个动态长度的数组,而不是从头开始编程,您应该使用标准 API 中为您提供的数组:java.util.ArrayList。在这里查看它的文档:http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html 。该类是 Java 集合 API 的一部分,这是任何 Java 程序员都必须了解的。在 Java tutorial 中学习如何使用它们.

您将拥有一个 PhoneRecord 列表,而不是 PhoneRecord[]:

List<PhoneRecord> records = new ArrayList<PhoneRecord>();

您可以添加新记录

records.add(newRecord);

如果需要,数组列表包裹的数组会自动增长。

您可以使用以下方式访问特定索引

PhoneRecord record = records.get(index);

您还可以像使用数组一样迭代列表:

for (PhoneRecord record : records) {
    // ...
}

关于java - Java中的数组增广问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5190996/

相关文章:

java - jpanel 表单 java 上有暂停/恢复按钮

java - 如何创建一个 .INI 文件以在 Java 中存储一些设置?

c++ - 如何检查 std::vector 超出范围的访问

php - 键存在于数组中时出现未定义索引错误

postgresql - 如何在 View 中捕获 'bigint out of range' 错误?

javascript - 自定义下拉焦点: call stack size exceeded

java - Checkstyle 和 PMD 仅作为建议

java - 仅从 JavaFX ObservableList 中获取一些值

javascript - JS 在对象而不是数组上应用数组原型(prototype) "indexOf"和 "splice"

java - 带数组的字符串输入