删除没有内置函数的方法

时间:2018-02-27 11:47:26

标签: java

这是我的代码,我需要从数组中删除水果

public void delete(String fruitName) {
    for (int i = 0; i < fruits.length; i++) {

        if ( fruits[i].equals(fruitName)) {
            fruits[i] = fruits[i+1];
            break;
        }
    }

// [“banana”,“apple,”芒果“]如果去掉香蕉然后输出[”apple“,”Mango“]。

    // TODO: 1. implement this method.
    /* TODO: 2. you may need to consult Java API documentation for the String class. 
     *          Write a comment in the code, the method of the String class you
     *          look up and the URL to the documentation the method 
     */
}

1 个答案:

答案 0 :(得分:0)

&#34;工作代码示例:&#34; (Execution)

public class DeleteValue {

    String fruits[] = { "apple", "orange", "banana", "mango", "Cherries", "Blueberries" }; // array of fruits

    public void delete(String fruitName) {

        // printing array of fruits before deletion
        System.out.println("\nAvailable fruits Before delete : " + fruits.length + "\n");
        for (String s : fruits) {
            System.out.println(s + " is Available\n");
        }

        int length = fruits.length;
        int lengthNew = length;
        int countNull = 0;

        // 1. Find and delete the fruit
        for (int i = 0; i < fruits.length; i++) {

            if (fruits[i] == fruitName) {
                fruits[i] = null;
                break;
            }

        }

        // count the null or deleted values so that we can create a new array of length
        // minus the deleted fruit
        for (int i = 0; i < fruits.length; i++) {

            if (fruits[i] == null) {
                countNull++;

            }

        }

        // new array length
        lengthNew = lengthNew - countNull;

        // create new array of fruits
        String newFruits[] = new String[lengthNew];

        // assigning values from original array to new
        int j = 0;
        for (int i = 0; i < fruits.length; i++) {

            if (fruits[i] == null) {
                continue;

            }
            if (fruits[i] != null) {
                newFruits[j] = fruits[i];
                j++;

            }

        }
        System.out.println("------------------------------------------");

        System.out.println("\nAvailable fruits after delete : " + newFruits.length + "\n");

        // print the final output
        for (String s : newFruits) {
            System.out.println(s + " is Available\n");
        }

    }

    public static void main(String args[]) {

        new DeleteValue().delete("mango");
        ;
    }

}

说明:

  

我唯一的问题是我的水果阵列没有减少   大小

array是一个容器对象,它包含固定数量的单一类型的值。创建数组时,将建立数组的长度。创建后,其长度是固定的

所以我们可以做的是使用动态数组,或者我们可以使用类似上面代码的解决方法:

如果你想&#34;成长&#34;或&#34;收缩&#34;在现有数组中,您必须分配一个适当大小的新数组,并将数组元素从旧数组复制到新数组。

在上面的代码中,我提供了有关工作步骤的注释。

我们解决这个问题有三个步骤:

  1. 从数组中查找并删除水果项。
  2. 从旧数组中计算已删除的值,以便我们可以创建一个新数组 那个大小。
  3. 将所有剩余项目从旧数组移至新数组。