jrsk8chivas
jrsk8chivas

Reputation: 43

Deleting element from an array in java

I created a program where users enter a command which are : adding a number to the array or delete an element from the array or print the array. The array size is 10.

Here is the tester class,

   import java.util.Scanner;
   public class Assignment7 {

   public static void main (String [] args) {

    Scanner scan = new Scanner (System.in);
     final int MAX = 10;
      Numbers nums = new Numbers(MAX);

     char command;
     int value;

     System.out.println
       ("To add an element into the array, type a.");
      System.out.println
     ("To delete an element from the array, type d.");
     System.out.println
     ("To print the current contents of the array, type p.");
      System.out.println
      ("To exit this program, type x.\n");
      System.out.print
      ("Add (a), delete (d), print (p) or exit (x)?:");

      command = scan.nextLine().charAt(0);
       while (command != 'x') {
      if (command == 'a' || command == 'd') {
      System.out.print ("Enter a number: ");
       value = scan.nextInt();
       scan.nextLine();
      if (command == 'a')nums.add(value);
        else nums.delete(value);
        }
       else if (command == 'p') nums.print();
         else System.out.println ("Not a value input");

        System.out.print
        ("Add (a), delete (d), print (p) or exit (x)?: ");
        command = scan.nextLine().charAt(0);
         }
         System.out.println ("Program Complete");
      }
   }

And here is my other class,

       import java.util.*;

       public class Numbers{
    private int[] nums;
    private int size;

    public Numbers(int _size){
    this.nums = new int[_size];
    }

    public void add(int addnum){
    if (size == nums.length)
    {
        System.out.println("Array is full. The value " +addnum + " cannot                be added.");
    }
    else
    {
    nums[size] = addnum;
    size += 1;
    }

        }

      public void delete(int deleteNum){
    if(search(deleteNum) == -1)
    {
    System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
    }
    else {
        for (int i = nums[deleteNum]; i < nums.length -1; i++){
            nums[i]= nums[i+1];
        }
    }
     }

      public void print(){
    String output ="";
    for(int str: nums){
    output = output + " " + str;
        }
    System.out.println(output);

     }

     private int search(int x){
    int index = 0;
    while(index < size){
        if(nums[index] == x)
        return index;
        index++;
            }
        return -1;
        }
       }

Each time I run the program and input a number I want to delete it doesn't delete it. It deletes the number in the index.

For example, if the array inputs are 1,2,3,4,5,6,7,8,9,10 and I want to delete the number 1 it deletes the value that is in the index of 1 which would be the number 2 instead of the number 1.

Upvotes: 2

Views: 5727

Answers (3)

Parnit
Parnit

Reputation: 1032

In your delete method, you should store the value you get from your search method. Right now you are calling nums[deleteNum] which is using the number inputted as an index. This is why you are having value 2 deletes. you should do something like this:

public static void delete(int deleteNum){
   int index = search(deleteNum);
    if(index == -1)
    {
    System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
    }
    else {
        int size = nums.length;
        for (int i = index; i < size; i++){
            if(i < (size-1)
                nums[i]= nums[i+1];
            else
                nums[i] = 0; //set to some base case or zero
        }
    }
     }

You will not be able to "delete" the last value, but instead have to set it to some base case. If you want to truly delete i. you should use another data structure, ie ArrayList

Upvotes: 0

Martin
Martin

Reputation: 1140

tl;dr: use an ArrayList, or seperate your array operations into its own class.

If you want to be able to add to and delete from a list, you most probably want to use an arraylist, which is implemented with an array "beneath the hood", but it supports a dynamic size. The most valid reason for you to use an array, and not some sort of collection is for learning purposes, in which case you should make your own "arraylist" so all code related to add/deleting/etc is contained within its own class. Just know that your implementation is probably never gonna be as efficient and robust as ArrayList.

When deleting elements you do not need to "resize" the array, only keep a seperate size variable which tells you which indeces are "valid". When adding new elements you have to initialize a new array with a greater size, if you have exceeded the array's length, and copy over all the elements from the old one.

Upvotes: 1

Simon Dorociak
Simon Dorociak

Reputation: 33495

I think that your "design" is not efficient. Because in your small program your array size is changing during runtime. Also your delete method is "weird".

Why it's not efficient?

You're using static array that has fixed size -> so if you want to "correctly" delete item from it, you need to re-initialise new array with new (size - 1)1 and this is such a spaghetti code operation.

And what is a suggestion?

What about to use dynamic array that can change its size dynamically when you'll remove or add new item to it? It also offers directly methods like add and remove for manipulating with it.

1You need to reinitialise static array (with new size - 1) again because if you'll "delete" for example 2. item from it it will be only assigned to zero so whole array will looks like: [ 1, 0, 3, 4, 5, 6, 7, 8, 9 ] and desired goal is [ 1, 3, 4, 5, 6, 7, 8, 9 ]

Upvotes: 1

Related Questions