Returning a formatted string does not working properly

3.2k views Asked by At

I have created a dupe-check that makes sure that newly created usernames are unique.

It looks like this:

String p1 = <code>; //First 3 chars in first name
String p2 = <code>; //First 3 chars in last name
int p3 = 1;         //Unique identifier.
boolean dupeCheck;

do {
  dupeCheck = false;
  for (int i = 0; i < userNameList.size(); i++) {
    if (userNameList.get(i).equals(p1+p2+Integer.toString(p3))) {
      dupeCheck = true;
      p3++;
    }
  }
} while (dupeCheck == true);

This works, if i return:

return String.format("%s%s%d", p1, p2, p3);

Duplicate usernames get names like:

  • xxxyyy1
  • xxxyyy2
  • xxxyyy3

Which is great. But i want the unique identifier (p3) to allways be three digits long. This is where String.format comes into play, along with my problems.

If i return the following code:

return String.format("%s%s%03d", p1, p2, p3);

For some reason, the dupe check fails and i get these usernames:

  • xxxyyy001
  • xxxyyy001
  • xxxyyy001

Can anyone explain what is happening?

2

There are 2 answers

1
dosw On BEST ANSWER

If you store usernames using %03d, i.e. with leading zeros, you also should use this when you compare the string in your userNameList:

userNameList.get(i).equals(String.format("%s%s%03d", p1, p2, p3))
0
griFlo On

like said in the comment: you store your name not the same way you compare it. you could also change your method this way:

    String p1 = "xxx"; //First 3 chars in first name
    String p2 = "yyy"; //First 3 chars in last name
    int p3 = 1;         //Unique identifier.


    while(true){ 
        if(userNamesList.contains(String.format("%s%s%03d", p1, p2, p3))){
            p3++;
        }
        else{
            return String.format("%s%s%03d", p1, p2, p3);
        }       
    }