I have here a scanner in which collects series of numbers. I want it to scan the list every time user inputs a number so if the user inputs a number that is already in the list the new input will be disregarded/ignored and at the same time not adding increment to the loop.
The problem is the code can't seem to identify the duplicates. It continues to register the duplicate number even after few tries.
My code so far:
public class Number {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How Many Numbers You want to Enter:");
int n = input.nextInt();
List<Integer> number = new ArrayList<>();
for(int s=0;s<n;s++) {
int t = input.nextInt();
for (int j = 1; j < number.size(); j++) {
if (t == number.get(j)) {
System.out.print("Duplicate!");
s--;
continue;
} else {
number.add(t);
}
}
}
}
}
At the moment nothing at all is being saved in the number list, so the first thing to do is add debugging to work out why, or better yet, we can make use of the ArrayList.contains(...)
method to solve this quite easily without needing the nested loop that that is causing your issue, for example the following works:
for(int s=0;s<n;s++) {
int t = input.nextInt();
if(number.contains(t)){
System.out.print("Duplicate!\r\n");
s--;
continue;
} else {
number.add(t);
}
}
//Print the result
System.out.println(Arrays.deepToString(number.toArray()));
And an output for a length of 5 and this number sequence 2,3,7,3,5,1 is:
How Many Numbers You want to Enter:5
2
3
7
3
Duplicate!
5
1
[2, 3, 7, 5, 1]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments