java - 如何删除数组中最后一个输入元素?

标签 java arrays input indexoutofboundsexception array-algorithms

对于这个程序,我使用 private static void add() 方法让用户将元素输入到 5 空间数组中。添加这些元素后,用户就可以使用private static void delete()方法,该方法允许他们输入他们希望删除的数组中存在的数字。当输入要删除的数字时,程序工作得很好,除非我尝试删除数组 currentSize 的最后一个数字。例如,如果我有一个具有以下索引和值的数组:

0. = 1
1. = 2
2. = 3
3. = 4
4. = <empty>

数组的 currentSize 当前为 4。如果我尝试删除索引 3 中的值 4,程序将不会删除值 4。如果我尝试删除值 3、2 或 1尝试删除值 4 后,这些值也不会删除。另一方面,如果我想首先删除值 4 以下的任何值,即值 1、2 和 3,则程序会正常工作,直到我尝试删除索引 0 中的值 4。如果我尝试删除值 4此时,没有任何内容被删除。如果我尝试添加一个值(例如 1),则在尝试删除值 4 后,值 4 会替换为值 1。如果我尝试在索引 0 处删除值 4 两次,然后尝试添加新值,则会收到 IndexOutOfBoundsException:-1。我相信这与 currentSize-- 递减有关,而在 private static void delete() 方法中存在的删除元素算法中不应有这种递减。如果有人对此有解决方案,将不胜感激,谢谢。程序贴在下面。我已经评论了给我带来问题的 private static void delete() 方法部分。这是我得到的堆栈跟踪:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at ArrayManager.add(ArrayManager.java:35)
    at ArrayManager.main(ArrayManager.java:216)
<小时/>
/**
 * A class that contains methods to carry out the Add, Update, Delete, Drop, Resize, and End commands to alter the state of an array with 5 integers.
 */
public class ArrayManager
{
    // Array of 5 integers to be modified
    private static int [] values = new int [5];

    private static int currentSize = 0;
    private static int position = 0;
    //private static int index = 0;

    static Scanner in = new Scanner(System.in);

    /**
     * A method that inserts an entered value into the array as long as it is between 1 and 99. If the array is full, an error message will be printed explaining that the array is full.
     */
    private static void add()
    {
        System.out.println("Enter values between 1 and 99, inclusive that you would like to add to the array.");
        if(in.hasNextInt())
        {
            int n = in.nextInt();
            if(n >= 1 && n <= 99)
            {
                if(currentSize < values.length)
                {
                    values[currentSize] = n;
                    currentSize++;
                }
                else
                {
                    System.out.println("ERROR: The array is currently full.");
                }
            }
            else
            {
                System.out.println("ERROR: The number entered must be between 1 and 99, inclusive.");
            }
        }
        else
        {
            System.out.println("ERROR: String has been entered. Enter an Integer.");
        }
    }
<小时/>
/**
     * A method that asks the user to enter a value they wish to delete in the array. The following values are then shifted down in index in the array. If the value chosen does not exist in the array, an error message is displayed explaining that the value entered does not exist in the array.
     */
    private static void delete()
    {
        int n = 0;
        System.out.println("Please enter the value in the array that you wish to remove.");
        if(in.hasNextInt())
        {
            n = in.nextInt();
            for(position = 0; position < values.length; position++)
            {
                if(values[position] == n)
                {
                 // The stack trace points me back to this section of code which removes the specified value in the values array.
                    for(int i = position + 1; i < currentSize; i++)
                    {
                            values[i - 1] = values[i];
                            values[i] = 0;
                    }
                    currentSize--;
                    break;
                }
                else if(position == values.length - 1)
                {
                    System.out.println("ERROR: The value entered does not exist in the array.");
                }
            }
        }
        else
        {
            System.out.println("ERROR: String has been entered. Enter an Integer.");
        }
    }
<小时/>
/**
     * A method that prints out the modified array.
     */
    public static void printArray()
    {
        System.out.println("* Current Array Contents *");
        for(int i = 0; i < values.length; i++)
        {
            if(values[i] != 0)
            {
                System.out.println(i + ". = " + values[i]);
            }
            else if(values[i] == 0)
            {
                System.out.println(i + ". = <empty>");
            }
        }
    }

最佳答案

位置是值数组最后一个元素的索引的极端情况未正确处理。在这种情况下,代码开始从下一个索引开始迭代元素,以便将所有元素移动 1 个位置,并且 for 循环中的条件不满足该条件。

for(int i = position + 1; i < currentSize; i++)

    for(int i = position + 1; i < currentSize; i++)
    {
        values[i - 1] = values[i];
        values[i] = 0;
    }

解决方案是检查该条件并明确处理它。

   if(values[position] == n ) {
       if( position != values.length - 1 ) {
           for(int i = position + 1; i < currentSize; i++)
           {
               values[i - 1] = values[i];
               values[i] = 0;
           }
       } else {
           values[i] = 0;
       }
       currentSize--;
       break;
   } 

关于java - 如何删除数组中最后一个输入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32922862/

相关文章:

java - 在 Java 中将动态变量与线程一起使用

Java Swing Ghost 组件 - JFrame 内水平框内的 JSplitPane

java - Java Netbeans 中的 hibernate 错误

C++ 超出下标范围

C++ 读取不带逗号的用户输入

Java 用户输入 - 输入一定范围内的整数或循环并重试

java - 使用 Maven 和 JNI 进行 CMake

javascript - 如何按动态对象数组过滤数组?

Java板数组问题

css - 输入元素在 IE7 中不可用?