Skip to content
Advertisement

Find unique character in a string ? What is wrong in logic . I’m unable to find error

I am trying to find characters that occur exactly once in a string, where the string contains only letters.

Here’s my code:

public static void main(String[] args)
{
    int count=0;
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter the string: ");
    String s=sc.nextLine();
    char ch1=s.charAt(0);
    if(s.matches("[A-Za-z]+"))
    {
        for(int i=0;i<s.length();i++)
        {
            System.out.println(s.length());
            System.out.println(ch1);
            for(int j=1;i<s.length();j++)
            {
                if(s.charAt(i)==s.charAt(j))
                {
                    count++;
                }               
            }
            if(count == 1)
            {
                System.out.println(s.charAt(i));
            }
                
        }
    }
    else
        System.out.println("Invalid");  
}

I’m getting a StringIndexOutOfBoundsException.

What am I doing wrong?

Advertisement

Answer

Try and initialize counter inside the first loop (Or since its not being used outside the loop, shift the declaration). The way you are initializing it (once) for the entire program will keep on increasing the value even when you move to the next character. Also, since you are testing using 1, change the inner loop initialization to 0 and the condition to j (its currently i)

import java.util.*;
import java.lang.*;

public class UniqueChar
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the string: ");
        String s = sc.nextLine().toLowerCase(); //good idea to change casing
        char ch1 = s.charAt(0);

        if (s.matches("[A-Za-z]+"))
        {
            for (int i = 0; i < s.length(); i++)
            {
                int count = 0; // initialize here
                System.out.println(s.length());
                System.out.println(ch1);

               for (int j = 0; j < s.length(); j++) // changed initialization to 0 and condition to j
                {
                    if (s.charAt(i) == s.charAt(j))
                    {
                        count++;
                    }               
                }
                if (count == 1)
                {
                    System.out.println(s.charAt(i));
                }
                    
            }
        } else {
            System.out.println("Invalid");  
        }
    }
}

Also, its a good idea to change the input to a uniform casing. The current setup will treat A and a as different, unless thats the requirement (in which case you should ignore the toLowerCase).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement