• Post Reply Bookmark Topic Watch Topic
  • New Topic

comparing a char?  RSS feed

 
Suka Hati
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i tried to make a comparison between 2 character. one character is from user and another character is a dash "-". i tried to compare it like this :

if (testelement.compareTo("-")>0|testelement.compareTo("-")<0)
then if its true, it will add a value of 1 to counter

but, i got this error when i try to compile it :

error : char cannot be dereferenced

how to solve my problem?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A char is simply a primitive value. It does not have any methods like compareTo or equals. However, you can easily compare char values in the same manner as you might compare int values. For example, if c1 == c2...

In contrast, a Character is an object that "wraps" a char value. Characters have many methods available to them, including compareTo or equals. So, once you've created Character objects c3 and c4, you could say, if c3.equals(c4)...

See the Java API for Character:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html

Note that literal char values must be enclosed by single quotes, because double quotes imply Strings. For example, 'a' is a char, but "a" is a String.
[ January 12, 2005: Message edited by: marc weber ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!