samedi 31 mai 2014

JAVA: How to remove duplicate values in a print array?


Vote count:

1




I have two methods, one method responsible for taking user input values (just numbers), for example:


The user inputs:



Enter a number: 76
Enter a number: 45
Enter a number: 45
Enter a number: 34
Enter a number: 32
Enter a number: 32
Enter a number: 32
Enter a number: 6
Enter a number: 7
Enter a number: 8
... etc


I then have another method with an array in it to display the output of what was just entered.



You entered: 76, 45, 45, 34, 32, 32, 32, 6, 7 ,8... etc


I want just each number to be shown once, example:



You entered: 76, 45, 34, 32, 6, 7 ,8... etc


How do I do this?



asked 52 secs ago


2 Answers



Vote count:

0




Use a Set. Those will only contain unique values.



answered 22 secs ago



Vote count:

0




Convert the array you have into a set which will get rid of duplicates and print.


E.g.



Integer[] values = {1, 2, 3, 3, 3, 4, 5, 5, 5};

Set<Integer> valueSet = new HashSet<Integer>(Arrays.asList(values));

for(int value : valueSet) {
System.out.println(value);
}


Hope it helps.



answered 10 secs ago





Aucun commentaire:

Enregistrer un commentaire