Niraj Singh
Niraj Singh

Reputation: 45

Why I am not able to find If my String contains only duplicate characters in my code in java?

Whenever I am passing all unique characters then it is returning true. For example niraj is coming as true but neeraj is also coming as true.

public class StringUniqueCharacters {
    public static void main(String[] args) {
        System.out.println("Enter any string");
        @SuppressWarnings("resource")
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();
        boolean stringUnique = false;
        stringUnique = isStringContainsOnlyUniqueChars(str);
        if (stringUnique)
            System.out.println("String has only unique character");
        else
            System.out.println("String has duplicate characters");
    }

    public static boolean isStringContainsOnlyUniqueChars(String str) {
        boolean flag = false;
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            for (int j = i + 1; j < chars.length - 1; j++) {
                if (chars[i] == chars[j])
                    break;
                else
                    flag = true;
            }
        }
        return flag;
    }
}

Upvotes: 0

Views: 57

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102804

Just go through your code: at i = 0, the loop starts with j = i + 1 (so, j starts at 1). if (chars[i] == chars[j]) boils down to if ('n' == 'e'), which is false, thus flag = true. You never set it back to false, so, when we eventually get to return flag;, true is returned.

Next time, instead of asking on SO, debug your code. Programmers aren't gifted crystal balls, we make mistakes and we solve it, not by asking someone else to look at it and pray they just sort of figure it out, but by debugging. Step through the code (with a debugger, or, if you must, with a boatload of System.out.println statements). First you calculate in your head what the line should do (what you expect to happen), then you check what actually happens. Where you find a discrepancy, you found a bug. Fix it, and move on to the next bug.

Keep going until you find no more bugs. Voila!

Upvotes: 2

Related Questions