0

I'm trying to find a way to find, and remove, duplicates in an ArrayList without using sets or hashes. This is what I have so far, but I keep getting the following error:

import java.util.*;

public class Duplicates 
{
	Scanner input = new Scanner( System.in );
	int i;
	ArrayList<Integer> numbers = new ArrayList<Integer>(5);
	
	
	public void EnterNumbers()
	{
		System.out.println("Please Enter 5 variables: ");
		for (i=0; i<5; i++)
		{
			System.out.printf("Please enter value in slot " + i + ":");
			numbers.add(input.nextInt());
		}
		System.out.println("ArrayList Values Are: " + numbers );
		
		for ( int j=0; j<=numbers.size(); j++)
		{
			if ( numbers.get(i).equals(numbers.get(j)))
			{
				numbers.remove(j);
			}
		}
		System.out.println("ArrayList Values Are: " + numbers );
	}
	
	
	public static void main(String[] args)
	{
		Duplicates DuplicateTest = new Duplicates();
		
		DuplicateTest.EnterNumbers();
	}
}

Error:

Please Enter 5 variables: 
Please enter value in slot 0:5
Please enter value in slot 1:4
Please enter value in slot 2:3
Please enter value in slot 3:2
Please enter value in slot 4:1
ArrayList Values Are: [5, 4, 3, 2, 1]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
	at java.util.ArrayList.RangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at Duplicates.EnterNumbers(Duplicates.java:26)
	at Duplicates.main(Duplicates.java:39)
1
Contributor
1
Reply
2
Views
6 Years
Discussion Span
Last Post by PDB1982
0

Ok, so I corrected the error, but how do I remove the duplicate values???

import java.util.*;

public class Duplicates 
{
	Scanner input = new Scanner( System.in );
	int i;
	ArrayList<Integer> numbers = new ArrayList<Integer>(5);
	
	
	public void EnterNumbers()
	{
		System.out.println("Please Enter 5 variables: ");
		for (i=0; i<5; i++)
		{
			System.out.printf("Please enter value in slot " + i + ":");
			numbers.add(input.nextInt());
		}
		System.out.println("ArrayList Values Are: " + numbers );
		
		for ( int j=i+1; j<=numbers.size(); j++)
		{
			if ( numbers.get(j).equals(numbers.get(i)))
			{
				numbers.remove(i);
			}
		}
		System.out.println("Adjusted Values Are: " + numbers );
	}
	
	
	public static void main(String[] args)
	{
		Duplicates DuplicateTest = new Duplicates();
		
		DuplicateTest.EnterNumbers();
	}
}

This is my current output:

Please Enter 5 variables: 
Please enter value in slot 0:5
Please enter value in slot 1:4
Please enter value in slot 2:5
Please enter value in slot 3:3
Please enter value in slot 4:2
ArrayList Values Are: [5, 4, 5, 3, 2]
Adjusted Values Are: [5, 4, 5, 3, 2]

Edited by PDB1982: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.