Matt
Matt

Reputation: 13

Java program to print first nonrepeating character in a string

public static void main(String[] args) {
        String str = "XXYZZA";

        char[] a = str.toCharArray();
        int count=0;
        for (int i = 0; i < a.length; i++) 
        {
            if (a[i] == a[i++]) 
            {
                count++;

            } 
            else
                System.out.println(a[i++]);

        }

    }

the print statement in the "else" part is not being executed. the desired output should be

Y
A

Upvotes: 0

Views: 97

Answers (2)

janith1024
janith1024

Reputation: 1042

Try like this, may help you

  public static void main(String[] args) {
    String str = "XXYZZA";

    char[] a = str.toCharArray();
    HashSet<Character> set = new HashSet<>();
    set.add( a[0]);
    for (int i = 1; i < a.length; i++)
    {
      if (!set.contains(a[i]) && (i+1 == a.length || a[i] != a[i+1]))
      {
        System.out.println(a[i]);
      }
      set.add(a[i]);

    }

Upvotes: 0

404 Brain Not Found
404 Brain Not Found

Reputation: 605

Ok, first and for-most, proper indentations please, helps out a lot to understand the code.

Secondly, if (a[i] == a[i++]) is not the right way to go because of 2 reasons

  1. your for loop will start skipping i values since you are using a unary operator, which will act directly on the operand.
  2. ArrayIndexOutOfBounds : once your i reaches its max value of a.length - 1 your test condition i++ will try to access the element at index a.length, which, as you might have guessed it, does not exist.

What you need is some sort of sorting algorithm without actually saving the sorted sequence.

Upvotes: 2

Related Questions