Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: comparing string but the '/0' keeps being counted

  1. #1
    Member
    Join Date
    Apr 2014
    Posts
    118
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default comparing string but the '/0' keeps being counted

    Ok I am trying to compare a string to see if all characters are unique. If there is a library for this or a better way to approach this do tell. However I find it important to understand what is going on behind the scenes.

    The issue is that the program counts the spaces '/0' and therefore everything will never be unique.

     
    public class CheckUnique
    {
     
    	private String sentence = "This will be compard";
    	private char[] checker;
    	private String isUnique = "The sentence is unique";
    	private String notUnique = "The sentence is not unique";
     
    	void checkString()
    	{
    		int[] count = new int[sentence.length()];
     
    		checker = new char[sentence.length()];
    		for(int i=0;i<sentence.length();i++)
    		{
    			checker[i]=sentence.trim().charAt(i);//copy characters of String into an array
    		}
     
    		for(int i=0;i<sentence.length();i++)
    		{
    		for(int j=0;j<sentence.length();j++)
    		{
    			if(checker[j]==sentence.charAt(i))
    			{
    			count[i]++;
    			//System.out.print(count[i]);
    			}
    			if(count[i]>2)
    			{
    				System.out.println(notUnique);
    				return;
    			}
    		}
    		}
    		System.out.println(isUnique);
    	}
     
     
     
    	public static void main(String[] args)
    	{
    		CheckUnique check = new CheckUnique();
     
    		check.checkString();
     
    	}
     
    }


  2. #2
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: comparing string but the '/0' keeps being counted

    Quote Originally Posted by jocdrew21 View Post
    I am trying to compare a string to see if all characters are unique.
    I'm not sure if I completely understand this... are you saying that you'd like to check if a string does not contain repeated letters (as opposed to characters, where space is a character)? Does this mean that "qw er ty" would be considered unique, whereas "qw er tyq" would not?

    Quote Originally Posted by jocdrew21 View Post
    However I find it important to understand what is going on behind the scenes.

    The issue is that the program counts the spaces '/0' and therefore everything will never be unique.
    Just add the printf statements indicated below to understand what's happening:
    ...
    for (int j = 0; j < sentence.length(); j++) {
     
        System.out.printf("checker[%d]: %c, sentence.charAt(%d): %c\n", j, checker[j], i, sentence.charAt(i));  // <== Add this
        if (checker[j] == sentence.charAt(i)) {
            count[i]++;
            System.out.printf("count[%d] = %d\n", i, count[i]);  // <== Add this
            // System.out.print(count[i]);
        }
    ...

    If you want to skip checking space characters, just add an if statement to check if checker[j] or sentence.charAt(i) is a space character. If it is, simply continue with the next iteration, skipping the rest of the processing for that iteration.

    Note that if you want to check if all the letters in a string are unique, then the "if (count[i] > 2)" statement will give you the wrong result.

    An alternative way to do this is:
    1. remove all space characters in a string by using the String.replaceAll(String, String) method
    2. get the length of the string (now with space characters removed)
    3. place all the characters into a Set (the Set will not have repeated characters since it can contain only unique elements)
    4. compare the size of the Set with the length of the string from #2

  3. #3
    Member
    Join Date
    Apr 2014
    Posts
    118
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: comparing string but the '/0' keeps being counted

    import java.util.Set;
     
    public class UniqueChecker
    {
     
    	private String sentence = "This will be compard";
    	private Set<String> checker;
    	private String isUnique = "The sentence is unique";
    	private String notUnique = "The sentence is not unique";
     
    	void checkString()
    	{
    		for(int i=0;i<sentence.length();i++)
    		{
    			checker.add(sentence);
    		}
     
    		if(checker.size()!=sentence.length())
    		{
    			System.out.println(notUnique);
    		}
    		else
    		{
    			System.out.println(isUnique);
    		}
    	}
     
     
     
    	public static void main(String[] args)
    	{
    		UniqueChecker check = new UniqueChecker();
     
    		check.checkString();
     
    	}
     
    }

    Very clever with using a set but am I using it wrong? How?

    I am coming from C++ and trying t use Java. I am not familiar with the libraries and really trying too.

    Exception in thread "main" java.lang.NullPointerException
    at UniqueChecker.checkString(UniqueChecker.java:16)
    at UniqueChecker.main(UniqueChecker.java:35)

    --- Update ---

    checker = new Set<String>();

    I tried this before my loop and this didn't work either.

  4. #4
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: comparing string but the '/0' keeps being counted

    The NullPointerException indicates that you're trying to perform some operation with a null. (See NullPointerException (Java Platform SE 7 ).) The operation in question is "checker.add(sentence)."

    Earlier in the class checker is declared as an instance variable (field):
    private Set<String> checker;
    However before you can do anything with it (such as calling the add(Object) method), you'll need to assign to the variable an instance of a class that implements the Set interface. HashSet is a good candidate; you can assign an instance of this class in the checkString() method:
    void checkString() {
        checker = new HashSet<String>();
        ...
    (See Creating Objects (The Java™ Tutorials > Learning the Java Language > Classes and Objects).)

    Once you've done so, checker will no longer be null, and you're then free to call the methods defined in the Set interface.

    You might be already familiar with the concept of "programming to an interface." Set is an interface. (See Interfaces (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance).) Therefore you did the right thing by declaring checker as a variable of type Set. However since you cannot instantiate an interface, "checker = new Set<String>();" will never work. Instead, you instantiate a concrete class that implements the interface, and this is where HashSet comes in.

    Btw, note that the following
    for(int i=0;i<sentence.length();i++)
    {
        checker.add(sentence);
    }
    adds the entire sentence String into checker repeatedly...

  5. #5
    Member
    Join Date
    Apr 2014
    Posts
    118
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: comparing string but the '/0' keeps being counted

    import java.util.HashSet;
    import java.util.Set;
     
    public class UniqueChecker
    {
     
    	private String sentence = "This will be compard";
    	private Set<String> checker;
    	private String isUnique = "The sentence is unique";
    	private String notUnique = "The sentence is not unique";
     
    	void checkString()
    	{
    		checker = new HashSet<String>();
     
    		for(int i=0;i<sentence.length();i++)
    		{
    			checker.add(sentence);
    		}
     
    		if(checker.size()!=sentence.length())
    		{
    			System.out.println(notUnique);
    		}
    		else
    		{
    			System.out.println(isUnique);
    		}
    	}
     
    	public static void main(String[] args)
    	{
    		UniqueChecker check = new UniqueChecker();
     
    		check.checkString();
     
    	}
     
    }

    I added the HashSet which is something I need to read more into. However you brought up a good point about how I am bringing copies of the string. I am really learning as I go. I tired getChar(i) but that failed. Any suggestions?

  6. #6
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: comparing string but the '/0' keeps being counted

    You might want to familiarise yourself with the String class: String (Java Platform SE 7 ). The String class does not have a getChar method. Instead it has a "getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)" method, which "copies characters from this string into the destination character array." Using this method will complicate things unnecessarily.

    The method to use is "charAt(int index)", which, incidentally, is one of the methods you previously used in post #1. The idea is to add each of the characters in a string into a set, and so you'd want to do something like:
    for (int i = 0; i < sentence.length(); i++) {
        checker.add(sentence.charAt(i));
    }

    The charAt method returns a primitive char type, whereas checker is declared as a Set<String> (i.e., a Set of String elements.) Therefore the next thing to do is to change checker so that it is a Set<Character> (a Set of Characters, where Character "wraps a value of the primitive type char in an object"), and make the corresponding change for HashSet as well.

    Note that apart from arrays, Java's data structures (e.g., Set) generally can only store objects (e.g., Character) and not primitives (e.g., char). However "checker.add(sentence.charAt(i));" will work. This is possible through autoboxing - the "automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes."

Similar Threads

  1. Java hangman help with comparing array to String
    By tonynsx in forum What's Wrong With My Code?
    Replies: 24
    Last Post: October 2nd, 2013, 04:50 PM
  2. [SOLVED] Hangman Program Java: Comparing the User's Guess with Another String Letter by Letter
    By theonlydvr in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 29th, 2013, 05:35 PM
  3. NullPointerException when comparing string in binary tree
    By tetkun in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 19th, 2013, 06:57 PM
  4. Replies: 1
    Last Post: April 19th, 2012, 02:46 AM
  5. error when comparing 2 string objects
    By amr in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 9th, 2011, 06:36 PM