简体   繁体   English

(Java) 从数组列表中删除所有出现的值

[英](Java) Removing all occurrences of a value from an array list

For my computer science class I need to make a program using IntegerList.java that completes the following:对于我的计算机科学课程,我需要使用 IntegerList.java 制作一个程序来完成以下内容:

  1. Add this capability to the IntegerList class.将此功能添加到 IntegerList 类。 You will need to add an increaseSize method plus instance variables to hold the current number of integers in the list and the current size of the array.您将需要添加一个 increaseSize 方法和实例变量,以保存列表中当前整数的数量和数组的当前大小。 Since you do not have any way to add elements to the list, you won't need to call increaseSize yet.由于您无法将元素添加到列表中,因此您还不需要调用 increaseSize。

  2. Add a method void addElement(int newVal) to the IntegerList class that adds an element to the list.将方法 void addElement(int newVal) 添加到 IntegerList 类,该类将元素添加到列表中。 At the beginning of addElement, check to see if the array is full.在 addElement 的开头,检查数组是否已满。 If so, call increaseSize before you do anything else.如果是这样,请在执行任何其他操作之前调用 increaseSize。

  3. Add a method void removeFirst(int newVal) to the IntegerList class that removes the first occurrence of a value from the list.向 IntegerList 类添加一个 void removeFirst(int newVal) 方法,用于从列表中删除第一次出现的值。 If the value does not appear in the list, it should do nothing (but it's not an error).如果该值未出现在列表中,则不应执行任何操作(但这不是错误)。 Removing an item should not change the size of the array, but note that the array values do need to remain contiguous, so when you remove a value you will have to shift everything after it down to fill up its space.删除项目不应更改数组的大小,但请注意,数组值确实需要保持连续,因此当您删除一个值时,您必须将其后的所有内容向下移动以填充其空间。 Also remember to decrement the variable that keeps track of the number of elements.还要记住减少跟踪元素数量的变量。

  4. Add a method removeAll(int newVal) to the IntegerList class that removes all occurrences of a value from the list.向 IntegerList 类添加一个 removeAll(int newVal) 方法,用于从列表中删除所有出现的值。 If the value does not appear in the list, it should do nothing (but it's not an error).如果该值未出现在列表中,则不应执行任何操作(但这不是错误)。 Add an option to the menu in IntegerListTest to test your new method.向 IntegerListTest 中的菜单添加一个选项以测试您的新方法。

I have finished everything except number 4 , which I am stuck on.我已经完成了除4之外的所有内容,我一直在坚持。 I'm not sure how to remove all occurrences of a value from the list.我不确定如何从列表中删除所有出现的值。 Here is my code for the rest of the program.这是我的程序其余部分的代码。

Integer List整数列表

public class IntegerList
{
    private int count;
    private double totalInt;
    int[] list; //values in the list

    //-------------------------------------------------------
    //create a list of the given size
    //-------------------------------------------------------
    public IntegerList(int size)
    {
        list = new int[size];
        count = 0;
    }

    //-------------------------------------------------------
    //fill array with integers between 1 and 100, inclusive
    //-------------------------------------------------------
    public void randomize()
    {
        for (int i = 0; i < list.length; i++)
            list[i] = (int)(Math.random() * 100) + 1;
    }

    //-------------------------------------------------------
    //print array elements with indices
    //-------------------------------------------------------
    public void print()
    {
        for (int i = 0; i < count; i++)
            System.out.println(i + ":\t" + list[i]);
    }

    public void increaseSize()//int size???
    {
        int[] temp = new int[list.length * 2];

        for (int i = 0; i < list.length; i++)
            temp[i] = list[i];

        list = temp;
    }

    public void addElement(int newVal)
    {
        if (count == list.length)
           increaseSize();

        list[count] = newVal;
        count++;
    }

    public void removeFirst(int newVal2)
    {
        int index = -1;
        for (int i = 0; i < count; i++)
        {
            index = i;

            if (index != -1) {
               // this code handles after found case
               if (i == count-1)
               {
                 // zero-out last element
                 list[i] = 0;
                 count--;
               }
               else
               {
                 // shift value
                 list[i] = list[i+1];
               }
            }
        }
    }

    public void removeAll(int newVal)
    {
       //This is the part I'm stuck on
    }
}

IntegerListTest整数列表测试

import java.util.Scanner;
public class IntegerListTest
{
    static IntegerList list = new IntegerList(10);
    static Scanner scan = new Scanner(System.in);

    //-------------------------------------------------------
    // Create a list, then repeatedly print the menu and do what the
    // user asks until they quit
    //-------------------------------------------------------
    public static void main(String[] args)
    {
        printMenu();
        int choice = scan.nextInt();
        while (choice != 0)
        {
            dispatch(choice);
            printMenu();
            choice = scan.nextInt();
        }
    }

    //--------------------------------------
    // Do what the menu item calls for
    //--------------------------------------
    public static void dispatch(int choice)
    {
        int loc;
        switch(choice)
        {
            case 0:
                System.out.println("Bye!");
                break;

            case 1:
            System.out.println("How big should the list be?");
            int size = scan.nextInt();
            list = new IntegerList(size);
            list.randomize();
            break;

            case 2:
            list.print();
            break;

            case 3:
            System.out.println("What number would you like to add?");
            int newVal = scan.nextInt();
            list.addElement(newVal);
            break;

            case 4:
            System.out.println("What number do you want to remove? "
                + "(Removes first occurance.)");
            int newVal2 = scan.nextInt();
            list.removeFirst(newVal2);

            case 5: //This is the part I am stuck on
            System.out.println("What number do you wish to remove?"
                + "(Removes all occurances.)");


            default:
            System.out.println("Sorry, invalid choice");
        }
    }

    //----------------------------
    // Print the user's choices
    //----------------------------
    public static void printMenu()
    {
        System.out.println("\n Menu ");
        System.out.println(" ====");
        System.out.println("0: Quit");
        System.out.println("1: Create a new list (** do this first!! **)");
        System.out.println("2: Print the list");
        System.out.println("3: Add element to the list");
        System.out.println("4: Remove a value from the list");
        System.out.println("5: Remove all occurrences of a value from the list");
        System.out.print("\nEnter your choice: ");
    }
}

I would use the code you have already written with some slight modifications.我会使用您已经编写的代码,并稍作修改。 I almost never write a method with the return type of void.我几乎从不编写返回类型为 void 的方法。 I want to have the option to know if my method was successful or not.我想知道我的方法是否成功。 Returning a boolean for your removeFirst() can come in handy when debugging or testing (JUnit).在调试或测试 (JUnit) 时,为您的 removeFirst() 返回一个布尔值会派上用场。 Just because the method now returns a boolean doesn't mean you have to use it, you can still call the method in the same way you are right now in your code with仅仅因为该方法现在返回一个布尔值并不意味着您必须使用它,您仍然可以像现在在代码中一样调用该方法

list.removeFirst(newVal2);

You only need to modify your method removeFirst() to return a boolean instead of void.您只需要修改您的方法 removeFirst() 以返回一个布尔值而不是 void。

boolean removeFirst(int valToDelete) - 
    //True - found the value you were looking for and successfully removed it from the list
    //False - the value to delete doesn't exist in your list

Then all there is left to do is use that method in a while loop like so然后剩下要做的就是在像这样的 while 循环中使用该方法

boolean removeAll(int val)
{
    boolean retVal = false;
    do{
        retVal = removeFirst(val);
    }while(retVal);

    return retVal;
}

This simple modification to removeFirst() allows re-usability in your class这个对 removeFirst() 的简单修改允许在你的类中重用

As an example, Java's own ArrayList method for remove() returns a boolean例如,Java 自己的 ArrayList 方法remove()返回一个布尔值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM