Go to GoReading for breaking news, videos, and the latest top stories in world news, business, politics, health and pop culture.

How to Remove Points From an Array in Java

104 8
    • 1). Click the NetBeans icon to launch it. Select "File/New Project" from the list at the top of the NetBeans window and then select "Java Application" to create a new Java project.

    • 2). Create a function named "removePoints." This function will remove a selected point from the array, which is passed in and bears the identifier "remove." Write this inside your source code file:

      public static int[] removePoint(int remove, int[] points)

      {

      }

    • 3). Iterate through the array and count all the occurrences of the point you want to remove. This count value will be stored in a variable called "skip." You can accomplish this by writing this code inside the curly brackets of the removePoint function:

      int skip = 0;

      for(int i = 0; i < points.length; i++)

      { if(points[i] == remove) {skip++; } }

    • 4). Create a new array to store all the values of the first array except the ones to be removed. The size of this array will be calculated using the skip variable from the previous step, like this:

      int[] outputArray = new int[points.length - skip];

    • 5). Iterate through the array once again, but this time copy elements from the first array into the new one you created in the previous step. Only add elements to the list if they aren't meant to be removed. You can write the code like this:

      for(int i = 0; i < points.length; i++)

      { if(points[i] != remove) { outputArray[i - skip] = points[i]; }

      else { skip++; } }

    • 6). Return the new array. This array will have all occurrences of the point removed from it, and it will be resized accordingly. You can return the new array like this:

      return outputArray;

Source...

Leave A Reply

Your email address will not be published.