Return the first name that is not taken: name, then name + 1, name + 2, and so on. You may call isTaken(String n), which returns true if that name is taken.
If "sam", "sam1" and "sam2" are taken, nextFreeName("sam") returns "sam3".
10 strips: I1 to I10
String tryName = name; I1} I2num++; I3tryName = name + num; I4} I5return tryName; I6while (!isTaken(tryName)) { I7while (isTaken(tryName)) { I8public static String nextFreeName(String name) { I9int num = 1; I10Order: I9, I1, I10, I8, I4, I3, I2, I6, I5. Extra: I7
Lines with the same mark can go in either order.
public static String nextFreeName(String name) {
String tryName = name;
int num = 1;
while (isTaken(tryName)) {
tryName = name + num;
num++;
}
return tryName;
} Extra strip: while (!isTaken(tryName)) {. The loop keeps going WHILE the name is taken. With !, the loop never runs and the method returns "sam", which is taken.