Question

I was wanting to know if anyone could help me out with this problem. The purpose of the program is suppose to be that the user enters a year, say 1980 and the program returns the next year that has distinctive digits, distinctive being all the digits are different, for example 2013-2019, 2012 is not distinctive since the number two occurs twice, 2013-2019 are all distinct because the numbers only occur once.

User enters year Program calculates next year that has distinctive digits

This is the code I have right now. The only purpose of it right now is to return true if the number the user enters is distinct, I could only find a way of doing it with String type and charAt method. I don't think you can increment strings but if it is possible for the user to enter an int and the program keeps incrementing until it finds a number that is distinct but all I could come up with is a function that accepts string. Is there a similar method I could make with int as a parameter or is there a way I could possibly make it work with Strings?

 public static boolean hasDuplicates(String text){
        for(int i = 0; i < text.length() - 1; i++){
            for(int j = i + 1; j < text.length(); j ++){
                if(text.charAt(i) == text.charAt(j)){
                    return true;
                }
            }
        }

        return false;
    }

Any advice is appreciated. Also my apologies for the lack of tags. Edit: Thank you. Full code at http://pastebin.com/FQj1yeCk

Was it helpful?

Solution 2

You can use Integer.toString(i) to get a string from your int.

So, using the method you created:

//int 'year' entered by user
while(hasDuplicates(Integer.toString(year))) {
    year += 1;
}

OTHER TIPS

You can do it with int and then use modular arithmetic to find out individual digits, like so:

int num = 1950;

int thousands = (num / 1000) % 10;
int hundreds = (num / 100) % 10;
int tens = (num / 10) % 10;
int ones = num % 10;

System.out.printf("%d %d %d %d",  thousands, hundreds, tens, ones);

outputs 1 9 5 0.

Given

int i;

you can get its String value with Integer.toString(i).

To convert between String and int you can use Integer.parseInt(text) and it will give you back and Integer object that will be unboxed to an in if you want.

To convert the other way around you can box your int into an Integer object and call toString on it.

So you could create an overloaded method like so:

public static boolean hasDuplicates(int value){
    return hasDuplicates(new Integer(value).toString());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top