12dec1990
12dec1990

Reputation: 115

Comparing and removing 2 consecutive elements of an arraylist in java

The following program asks for user input which consists of integers.The program exits as the letter x is entered.As soon as the program ends,each element if the arraylist is inspected.The list is divided into sets of coordinates i.e every 2 elements are grouped together.

For example, if the arraylist consists of [2,3,4,5,7,8],the elements are grouped together as (2,3) (4,5) and (7,8).These are then compared together.If the left element is bigger than the right one,those 2 elements are removed. I have the following code that does recognize if the pairing is acceptable or not but fails to remove the elements.

import java.util.*;
public class ArrayLists {
    public static void main(String[]args)
    {
        ArrayList<Integer> myList=new ArrayList<Integer>();
        Scanner a=new Scanner(System.in);
        for(int i=0;i>=0;i++)
        {
            System.out.print("Enter whole number.Enter x to quit: ");
            if(a.hasNextInt())
            {


                int userinput=a.nextInt();
                myList.add(userinput);

            }
            else if(a.next().equals("x"))
            {
                break;
            }
        }
        //System.out.println(myList);


        for(int b=0;b<myList.size();b+=2)  //Inspects the arraylist starting from index 0.
        {
            int c=b+1;  //Inspects the list,starting from index 1.


        if(myList.get(b)>myList.get(c))
        {
            System.out.println("Crap!");
            //System.out.println("Index"+b+","+c);


            myList.remove(b);
            myList.remove(c);

        }
        else if(myList.get(b)<myList.get(c))
        {
            System.out.println("Goodjob!");

            }
        else
        {
            System.out.println("GoodJob!");
        }
        c=c+1;
        }
        System.out.println(myList);
        }    
        }

Upvotes: 0

Views: 2000

Answers (1)

karthik manchala
karthik manchala

Reputation: 13640

Assume current index of b = 0 and index of c = 1;

myList.remove(b); -> removes your 1st element and myList is modified such that 2nd element has become 1st element now

myList.remove(c); -> this logically will now delete 2nd element of modified myList.. that is 3rd element of unmodified myList.

You can just decrease c by 1 after removing b..

myList.remove(b);
c--;
myList.remove(c);

And also your iterating is wrong. increment b only if myList is unmodified.

you should must be doing this:

for(int b=0;b<myList.size();)

and this:

else if(myList.get(b)<myList.get(c))
{
    System.out.println("Goodjob!");
    b+=2;
}

HTH!

Upvotes: 1

Related Questions