Java if statement won't work.

Caporegime
Joined
12 Mar 2004
Posts
29,962
Location
England
Code:
if ((name.charAt(i)).isDigit())

Keep getting this error message

Code:
org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 9 in the jsp file: /Demo 2/mypage.jsp
Generated servlet error:
Cannot invoke isDigit() on the primitive type char
 
Code:
if ( Character.isDigit(name.charAt(i)) )

Edit: Incase you actually want to know why: name.charAt is returning the primitives type "char", primitives do not have methods. The isDigit method is a static method on the "Character" wrapper class, which is an object that wraps a char primitive.
 
Last edited:
Ah that's why, I thought the class char and character were the same thing, so when I looked at the api I couldn't understand why it didn't work.
 
Can someone also tell me why does this not work.

Code:
if (email.charAt(i) == "@")

Says incompatible types string and char, works fine in javascript but not java. I thought that "@" was a char?
 
Can someone also tell me why does this not work.

Code:
if (email.charAt(i) == "@")

Says incompatible types string and char, works fine in javascript but not java. I thought that "@" was a char?

@ is a char, but when you have it in "" it's a String, try replacing the "" with '@' so

Code:
if (email.charAt(i) == '@')
 
Ah that's why, I thought the class char and character were the same thing, so when I looked at the api I couldn't understand why it didn't work.

Occasionally you can kind of interchange them due to a feature called autoboxing but not really, its more like the ability for java to do "new Character(char)" on the fly:

http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

It's along the same lines that int is not Integer, long is not Long and boolean is not Boolean.

The wrapper classes provide other operations. One reason for the wrapper classes existing is because the primitives don't extend Object, so basically if you wanted to have an ArrayList<int> you can't do that because the Type Parameter that ArrayList expects must extend Object, so to get around this you put your int inside the Integer wrapper class which lets you put it in things that expect an Object. As you've found out though, the wrapper classes do provide some handy utility methods as well though.
 
Also note that String == "blah" or String == AnotherString is almost always wrong as you're doing a reference comparison rather than a String comparison. You should usually use String.equals(AnotherString).
 
Back
Top Bottom