14 Replies Latest reply: Nov 18, 2007 10:37 PM by 807600 RSS

    Removing an item from an array

    807600
      Hello sun forum,

      I wonder if anyone would be kind enough to assist a newbie Java hobbyist with a few basic questions?

      I don't want to take up too much of your time so I will be brief.

      I want to prompt a user for ten numbers, then print the numbers in a column one on top of the next. Then I want to prompt the user for a number to be removed from the list. After the number is entered, it is removed, and the remaining arrays are printed in a row.

      So far I have only written the code which prompts the user for the numbers, and the code which prompts the user for the number to be removed. I know how to print the array before the number is removed but I'm not sure how to print it in a column.
      Next, I know how to search the array for the number but I'm not sure how to remove the number and then print the row of remaining numbers.

      Here is a summary of the problem at hand:

      method removeAll removes all instances of RemoveItem from the array
           array of integers
           length of array
           integer to be removed
                RemoveItem
      method print
           accepts two parameters
                array
                array length
           prints array == to actual size of array
                no blank spaces


      program asks user for 10 integers
      then asks for number to be deleted

      array prints before number removed from list
      array prints after number is removed

      H.
        • 1. Re: Removing an item from an array
          807600
          To print in a column, just print each element and then a newline.
          Using System.out.println as opposed to System.out.print will do it.

          You can't remove an number from an array of (primitive) numbers. That's because in an array of primitives, each value in the array has a value. The default value is zero.

          There are a few things you can do:

          1) you can create a new array, one element smaller, and copy the old array to the new array, skipping the deleted element.

          2) You can decide that a certain number means "no number", and set the value in the given array position to that.

          3) you can have an array of, say, java.lang.Integers, and then use null to mean no integer

          4) you can keep an additional variable to indicate which position in the array is considered dead. Use that when you're printing out the array the second time.

          5) You can use a java.util.List instead of an array, and easily remove the item.

          And probably other things as well.

          Good luck on your homework!
          • 2. Re: Removing an item from an array
            807600
            Mr Paulcw,

            Thank you for your reply. I will try to use some of your suggestions. You offered so many approaches but I think the simplest is probably copying all the elements of the old array into the new one ( except the item that is being deleted).
            So option number one it is!
            • 3. Re: Removing an item from an array
              807600
              Hansen_Kadosh wrote:
              ....I think the simplest is probably copying all the elements of the old array into the new one ( except the item that is being deleted).
              So option number one it is!
              If you are looking for true simplicity and flexibility, you'd opt for option number 5. That's what I'd choose.
              • 4. Re java.util.list
                807600
                petes123,

                Hello. Thanks for your tip. I am not too familiar with this interface. Maybe I can use the remove method: public boolean remove(Object o)?
                The thing is, the arrays must be entered by the user not taken from a preset list.
                I'm not too familiar with the syntax of this method when trying to remove an item entered by the user rather than from a preset list.
                That is the only reason I find option #1 simpler...it is more familiar to me right now.

                This is where I am at now:
                import java.util.*;
                
                public class removeAll{
                static Scanner console = new Scanner(System.in);
                static final int arraySize = 10;
                
                public static void main(String[] args)
                {
                int[] intList = new int[arraySize]; //Line 1
                int removeNumber; //Line 2
                int index; //Line 3
                
                System.out.println("Line 4: Enter " + arraySize
                + " integers."); //Line 4
                
                for (index = 0; index < arraySize; index++) //Line 5
                intList[index] = console.nextInt(); //Line 6
                
                System.out.println(); //Line 7
                
                System.out.print("Line 8: Enter the number "
                + "to be removed: "); //Line 8
                removeNumber = console.nextInt(); //Line 9
                System.out.println(); //Line 10
                • 5. Re: Re java.util.list
                  807600
                  I often declare a List interface variable and then construct it with an ArrayList. At your stage in the game, you may just want to use the ArrayList variable and constructor. And yes, the remove method is one worth looking at.
                  • 6. Re: Re java.util.list
                    Darryl Burke
                    Hansen_Kadosh

                    Allow me to refer you to the Code Conventions for the JavaTM Programming Language
                    {color:#0000ff}http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html{color}
                    or download for perusal at leisure from
                    {color:#0000ff}http://java.sun.com/docs/codeconv/{color}

                    db
                    • 7. Re: Removing an item from an array
                      800308
                      Hansen,

                      If you're doing this for the learning experience then steam right ahead and use an array of primitives... but "low level" array manipulations such are this are mostly of "academic interest"... thankfully.

                      The standard java library has the "Collections framework" http://java.sun.com/docs/books/tutorial/collections/index.html which is designed specifically to deal with common problems associated with storing, sorting, filtering, slicing, splicing, dicing and otherwise messing about with groups of things... including your current: deleting an item from an array is a messy, tricky, & expensive business.

                      The Collections fraemwork allow us application programmers to spend our time (and our bosses money) more productively on "higher level concerns", like designing the service set, and does cyan & magenta work as colour scheme (not!)... and it's actually really rather clever to boot.

                      Cheers. Keith.
                      • 8. Re: Re java.util.list
                        807600
                        wow thanks everyone for the overwhelming response. I'm not sure where to start!

                        OK Petes 123,

                        Here is where I am at now. I finally figured out how to print out the array after the user enters the list. I know how to find the position of the array selected by the user, but even after looking through all these documents provided for me I can't seem to find a section that explains HOW to remove the array selected and then print what remains.

                        Right now I'm using a snippet of code from a program similar to the one I'm working on, only it shows the position of the array in the list while I am trying to show the list minus the array selected. This should be the last question and you all can go on to something more important.
                        import java.util.*;
                        
                        public class PrintRemoveAll
                        {
                        static Scanner console = new Scanner(System.in);
                        static final int arraySize = 10;
                        
                        public static void main(String[] args)
                        {
                        int[] intList = new int[arraySize]; //Line 1
                        int removeItem; //Line 2
                        int index; //Line 3
                        
                        System.out.println("Line 4: Enter " + arraySize
                        + " integers."); //Line 4
                        
                        for (index = 0; index < arraySize; index++) //Line 5
                        intList[index] = console.nextInt(); //Line 6
                        
                        System.out.println(Arrays.toString(intList)); //Line 7
                        
                        System.out.print("Line 8: Enter the number "
                        + "to be removed: "); //Line 8
                        removeItem = console.nextInt(); //Line 9
                        System.out.println(); //Line 10
                        
                        index = removeAll(intList, arraySize, removeItem); //Line 11
                        
                        if (index != -1) //Line 12
                        System.out.println(Arrays.toString(intList)); //Line 13
                        else //Line 14
                        System.out.println("Line 15: " + removeItem
                        + " is not in the list."); //Line 15
                        
                        }
                        public static int removeAll(int[] list, int listLength, int searchItem)
                        {
                        int loc;
                        boolean found = false;
                        
                        for (loc = 0; loc < listLength; loc++)
                        if (list[loc] == searchItem)
                        {
                        found = true;
                        break;
                        }
                        
                        if (found)
                        return loc;
                        else
                        return -1;
                        }
                        }
                        • 9. Re: Re java.util.list
                          807600
                          If you are going to work with arrays and not arraylists, then I recommend that you do paulcw recommendation&#153; number 1.
                          • 10. Re: Re java.util.list
                            807600
                            Petes 123,

                            Hi. Yes thanks. I think that is what I plan to do--PaulCW's trademarked suggestion.
                            I'll probably work with arraylists next but for now I'm going to use his suggestion. I'm almost there. I don't quite understand how to implement his suggestion though. I must look into it more I suppose. Thanks.

                            H
                            • 11. Re: Re java.util.list
                              807600
                              Well, you've prompted the user for the number to remove, right?

                              So you have some variable holding that number.

                              When you copy the values from the old array to the new array, check each one to see if it's that number. If it is, don't copy it.
                              • 12. Re: Re java.util.list
                                807600
                                Thanks Mr. Burke,

                                These documents will be really handy for upcoming experiments and this one too. I'm trying to scour through them and find a section that applies to my problem. I put down what I have so far but it isn't working correctly. I'm trying to print out the list after the number is removed, but so far I am only succeeding in printing out the number selected!

                                But thanks anyway. Have a good night.

                                H
                                • 13. Re: Removing an item from an array
                                  807600
                                  Keith,

                                  Hi. Hey thanks for your tip. I scoured through the documents you provided but I did not come across anything specifically related to this problem. But since I am a beginner may just not understand some of it or how it relates. For now, I'm just going through a college text on this subject and working through the problems in the book. It looks like this problem uses an academic solution since the book is, after all, an academic text.

                                  Paulcw has pretty much explained how to solve the final bit of this problem but I'm still scratching my head as to how you keep the new array from copying the selected number. But don't give it away. I'll figure it out. If I can't figure it out soon maybe I'll come back here with my tail between my legs in need of guidance:> Just a little more review I think...

                                  H
                                  • 14. OK thanks I got it.
                                    807600
                                    Everyone, thanks. No need for any more help. You've been great. May you all find programming questions that you don't hear over and over and that you actually find puzzling yourself...in a good way like, 'hmm how does this program for calculating the size of the universe work'? Rather than 'why doesn't this guy understand anything I'm saying to him?':>