Char cannot be dereferenced!! Please help
Hi all im working on a program and have got the error "char cannot be dereferenced". The for loop iterates through the array "people" and sends a message to each one using the method "getPerson()". This method gets a single character from a StringBuilder array. The method is declared as the return type char so i used .toString to try to change it into a string as I got a different error before. I am a novice in java so im not even sure im going about this theright way! I hope someone can help because I just cant see a way forward!
Thankyou in advance for anyone willing to help.
Code :
for (int i = 0; i < people.length; i++)
{
aHouse.getPerson();
{
if (aHouse.getPerson().toString() == "Y")
{
return "Yes";
}
}
}
Re: Char cannot be dereferenced!! Please help
Strings should be compared using the .equals() method.
Re: Char cannot be dereferenced!! Please help
I had already tried that before I posted but when I tried to compile it just kept telling me I needed a bracket on the line shown below and if I added a bracket it just continued giving that error:
Code :
for (int i = 0; i < people.length; i++)
{
aHouse.getPerson();
{
if (aHouse.getPerson().toString().equals == "Y") // compiler says i need an ) here
{
return "Yes";
}
}
}
Re: Char cannot be dereferenced!! Please help
it should be:
Code :
aHouse.getPerson().equals("Y")
if getPerson() returns a String you do not need to call toString().
also your first call to aHouse.getPerson() seems pointless to me, as you do not bother to store the returning Object the second call to aHouse.getPerson() does exactly the same thing.
Re: Char cannot be dereferenced!! Please help
Hi thankyou for the advice, I have changed the code so its a you say but I get the same char cannot be dereferenced error when i try to compile.
Re: Char cannot be dereferenced!! Please help
.toString() is an instance method for Objects. You say your getPerson() method is returning
a char; a char is a primitive data type, not an Object! Just compare the returned value directly
to the character 'Y' (note that inverted commas are used to denote character literals, and
quotation marks for string literals).
Code :
if(aHouse.getPerson() == 'Y')
{
//do stuff
}