0

This is a simple programme for array in java. I want delete a number at user want but it is not working in my code, last two element is proper working but at the starting of element deleting is not working and i don't want to use of ArrayList in my code.delete one element at user want which is present in array.

import java.util.Scanner;

public class delete {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        System.out.println("pls enter the size of an array:-->");
        int n=in.nextInt();

        int num[]=new int[n];
        for(int k=0;k<num.length;k++)
        {
            System.out.println("enter the value:--> "+(k+1));
            num[k]=in.nextInt();
        }

        System.out.println("Enter the number to be delete:-->");
        int m=in.nextInt();

        for(int p=0;p<num.length-1;p++)
        {
            if(m==num[p])
            {
                  num[p]=num[p+1];      
             }

        }

        for(int k=0;k<num.length-1;k++)
            System.out.println(num[k]);

    }

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Verma
  • 19
  • 2
  • 9
  • Why the downvotes? Perfectly fine code, a very specific question/problem. Rare to see positive votes in the java tag.. – arynaq Oct 19 '14 at 19:30
  • Everyone sees that it wont delete, only cover the number with the next number in array..., and surely wont work for last element @arynaq – maskacovnik Oct 19 '14 at 19:31
  • For a novice programmer it's not clear that it wont delete. I think what he is trying to do, is to remove the n'th element, by overwriting it with the n+1'th element, and then overwrite the n+1'th element with the n+2'th element, etc, until the loop terminates at the second last element. – Andersnk Oct 19 '14 at 19:34
  • @Verma Why don't you use a dynamic collection : like ArrayList ? A usage example here : http://stackoverflow.com/questions/2697182/how-to-use-an-array-list (Just call list.remove(index) in order to remove element at index). – loloof64 Oct 19 '14 at 19:37

1 Answers1

1

I would recommend you to use ArrayList instead of just an array (check the java documentation for more informatio), but if you want to do it this way it should be like this:

Just add this line

for(int p=0;p<num.length-1;p++)
    {
        if(m==num[p])
        {
            num[p]=num[p+1];

            // Add this line
            m = num[p];
        }
    }

this is because when you find the number, you just were changing the value of the next element, instead of all the remaining elements

One thing you should note is that you are not deleting the element, just overwriting the values.