1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Sort
{
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
    Boolean checker = false;
    String regex = "^(?:([0-9])(?!.*\1))*$";
    Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);

    System.out.println("Enter the Year:");
    String number = input.next();
    int year = Integer.valueOf(number);

    Matcher matcher;
    while(!checker) {
    matcher = pattern.matcher(number);
    if(matcher.find())
        checker = true;
    else
        year++;
        number = Integer.toString(year);
  }
  System.out.println(number);

 } 
}

My friend and I are trying to create an algorithm to calculate the next number after an inputed number that will have not repeated numbers (e.g. input: 1000 output: 1023).

The code of interest is:

    Matcher matcher;
    while(!checker) {
    matcher = pattern.matcher(number);
    if(matcher.find())
        checker = true;
    else
        year++;
        number = Integer.toString(year);
  }

For some reason the checker will be set to true even though the matcher.find() is false. The outcome for every output will then result in the same value as the input.

What is wrong and how would we change our logic so that the checker returns false when digits in a number are repeated?

ylun.ca
  • 2,504
  • 7
  • 26
  • 47

1 Answers1

1

Consider these lines

 if(matcher.find())
   checker = true;
 else
   year++;
   number = Integer.toString(year);

There are a few problems. I think you're missing braces. And you've forgotten to update checker when matcher.find() is false. I suggest you do this instead

checker = matcher.find();
if (!checker) { // checker is not true... e.g. checker == false.
  year++;
  number = Integer.toString(year); // I assume you wanted this here.
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249