Home > front end >  not getting correct input for checking for duplicates
not getting correct input for checking for duplicates

Time:11-01

for the problem, i am required to take in 10 integers, and then print out the unique numbers. My problem solving approach for this was to scan all the numbers behind the one we are checking to see if there are any duplicates. here's the code I have so far. if i enter in numbers like "1234567891", it only will print "pl: 1" because I add the first number before running the algorithm. Any hypothesis on why it's not working?

//setup
Scanner input = new Scanner(System.in);
String text = input.nextLine();
text = text.replaceAll("\\s",""); //remove all spaces
int[] intDigits = new int[10];

//turn the string into an int array
for (int i = 0; i < 10; i  ){
    intDigits[i] = text.charAt(i) - '0';
}
input.close();

//add the first number since it will always be unique with my algorithm
String pl = intDigits[0]   " ";

//check every number behind the one we are checking, if all the numbers are not equal to the one we are checking, then add it to the string of unique numbers.
for (int i = 1; i < 10; i  ) {
    int count = 0;
    for (int j = i-1; j >= 0; j--) {
        if (intDigits[i] != intDigits[j]) {
            count  ;
        }
    }
    if (count == i-1) {
        pl  = intDigits[i];
    }
}
System.out.println("\n\npl: "   pl);

CodePudding user response:

The issue is with if (count == i-1). Instead it should be if (count == i).
Since you are checking from index 1, count will be 1(j=0) if no duplicate.
Similarly, for i=2 count will be 2(j=1,0) if no duplicate. And same for the rest.

  •  Tags:  
  • java
  • Related