【问题标题】:Add and delete items of Array in JavaJava中Array的添加和删除项
【发布时间】:2015-10-19 01:46:18
【问题描述】:

我一直想学习如何在数组中添加或删除元素。我知道在这些类型的东西上使用 Arraylist 包更容易,但我想学习如何在不使用它的情况下添加或删除元素。我曾尝试为此创建代码,但最终出现了一些错误。

我的代码的输出应该是这样的:

********************^

1 - Search Name
2 - Add Name
3 - Delete Name
Enter mode:2
Enter new name:professor x
Do you want to add a name again?(y/n):y
Enter new name:professor y
Do you want to add a name again?(y/n):n

********************^

1 - Search Name
2 - Add Name
3 - Delete Name
Enter mode: 1
Enter name:professor x
Match found!

但在搜索以前输入的记录时,我的代码给了我一个null pointer exception:

Exception in thread "main" java.lang.NullPointerException
at Practice.Practice1Main.sequentialSearch(Practice1Main.java:95)
at Practice.Practice1Main.mode(Practice1Main.java:18)
at Practice.Practice1Main.getMode(Practice1Main.java:79)
at Practice.Practice1Main.caseTwo(Practice1Main.java:63)
at Practice.Practice1Main.mode(Practice1Main.java:33)
at Practice.Practice1Main.getMode(Practice1Main.java:79)
at Practice.Practice1Main.main(Practice1Main.java:6)

我的代码:

package Practice;
import java.util.Scanner;
public class Practice1Main {
    public static void main(String[]args){
        getMode();
    }
    public static void mode(int mode){
        Scanner hold = new Scanner(System.in);
        int numInput = 2;
        String[] names = new String[numInput];
        String response = "";
        if(mode == 1){
            do{
                int result = sequentialSearch(names, getNames());
                if(result == -1){
                    System.out.print("No match found!\n");
                }else{
                    System.out.print("Match found!\n");
                }
                System.out.print("Do you want to search again?(y/n):");
                response = hold.nextLine();
                if(response.equalsIgnoreCase("n")){
                    getMode();
                }
            }while(response.equalsIgnoreCase("y"));
        }else if(mode == 2){
            caseTwo(response, names, numInput);
        }else if(mode == 3){
            // TODO: Part 3
        }else{
            System.out.print("ERROR 350\n");
        }
    }

    public static void caseTwo(String response, String[] names, int numInput){
        Scanner hold = new Scanner(System.in);
        do{
            int x = 0;
            System.out.print("Enter new name:");
            names[x] = hold.nextLine();
            System.out.print("Do you want to add a name again?(y/n):");
            response = hold.nextLine();
            if(response.equalsIgnoreCase("y")){
                x++;
                if(x == 2){
                    int add = numInput + 1;
                    names = new String[add];
                    System.out.print("Enter new name:");
                    names[add] = hold.nextLine();
                    System.out.print("Do you want to add a name again?(y/n):");
                    response = hold.nextLine();
                    if(response.equalsIgnoreCase("y")){
                        add++;
                    }
                }
            }else if(response.equalsIgnoreCase("n")){
                getMode();
            }else{
                System.out.print("CASE 2 ERROR!\n");
            }
        }while(response.equalsIgnoreCase("y"));
    }

    public static void getMode(){
        Scanner hold = new Scanner(System.in);
        int mode;
        System.out.print("********************\n");
        System.out.print("1 - Search Name\n");
        System.out.print("2 - Add Name\n");
        System.out.print("3 - Delete Name\n");
        System.out.print("Enter mode:");
        mode = hold.nextInt();
        mode(mode);
    }
    public static String getNames(){
        Scanner hold = new Scanner(System.in);
        String name;
        System.out.print("Enter name:");
        name = hold.nextLine();
        return name;
    }
    public static int sequentialSearch(String[]names,String name){
        int index = 0;
        int element = -1;
        boolean found = false;
        while(!found && index < names.length){
            if(names[index].equalsIgnoreCase(name)){
                found = true;
                element = index;
            }
            index++;
        }
        return element;
    }
}

【问题讨论】:

  • 你不能在java中调整数组的大小
  • 您是否有理由不能使用 ArrayList 或者您只是不想使用?数组在声明时具有固定大小,因此您不能“添加”或“删除”,只能在索引处重新分配值。
  • 你应该修正你的帖子标题,你不小心把所有的大写字母都放了。
  • 我会按照其他人的建议使用数组列表。它更易于使用,并且可以按照您的意愿工作。

标签: java arrays


【解决方案1】:

任何时候输入mode() 方法,都会重新初始化names 数组。这就是为什么它只包含 null 值,因此是 NullPointerException。你应该让它成为类的一个字段。

此外,按照设计,它的长度始终为 2。

【讨论】:

    【解决方案2】:

    ArrayList 在功能上正是您正在寻找的,而我即将为您提供的替代方案将完全按照 ArrayList 所做的工作,但效率或吸引力要低得多。作为免责声明,我会说你应该学习使用 ArrayList,但无论如何我都会按照你的方式回答你的问题,同时你也会了解 ArrayList 的工作原理。

    要调整数组大小,无论如何都必须创建一个新数组。最有效的方法可能是使用临时数组来存储您的数据,然后像这样重新实例化您的主数组变量

    // Inside your adjustable array class. Let's call it "AdvArray"
    
    // A field that's instantiated inside the constructor
    int[] exampleArray = {1, 2, 3, 4, 5}; // create and fill an int array
    
    public void addElement(int element){
        //Make temp array the size of your data and fill it
        int[] tempArray = new int[exampleArray.length];
        for(int i = 0; i<exampleArray.length; i++){
            tempArray[i] = exampleArray[i];
        }
    
        //reinstantiate exampleArray and fill with old data
        exampleArray = new int[exampleArray.length+1];
        for(int i = 0; i<tempArray.length; i++){
            exampleArray[i] = tempArray[i];
        }
    
        //Add new element to larger array
        exampleArray[exampleArray.length-1] = element;
    }// ===================================================
    
    // Example usage
    exampleAdvArray.addElement(500);
    

    此方法在末尾添加一个,但您可以通过创建一个带有要添加到的索引的溢出来遵循它的想法,然后将两个过程反转为一个 remove 方法。然后,您需要做的就是为任何给定索引处的元素添加一个 getter,或者甚至可能是一个返回“exampleArray”字段的 getArray 方法。

    或者,您的代码如下所示:

    ArrayList<int> exampleList = new ArrayList<int>();
    for(int i=1; i<=5; i++){
        exampleList.add(i);
    }
    exampleList.add(500);
    

    【讨论】:

    • 如果您决定使用 ArrayList,它还有一个 indexOf 方法,该方法执行搜索并返回您输入的元素的索引。看起来像这样 exampleList.indexOf("Professor x"); // 返回 0,因为它是第一个元素
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2015-09-18
    • 1970-01-01
    • 2014-05-05
    • 2011-08-27
    • 2020-02-01
    相关资源
    最近更新 更多