Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Convert String to char and determining

 
Garry Meax
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whether its a specific character.

i declare grade1 as a String. then i convert it to char as follows:

(char)grade1

i want to check whether this((char)grade1) is equal or not to 'A'.

so i use,

if((char)grade1 != 'A')
{
s.o.pln("No")
}
else
{
s.o.pln("Yes")
}

am i right here?
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You cannot typecast a String to char.
String is an object whereas char is a basic data type.

You could try this instead:


Mehul.
 
Abdulla Mamuwala
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gary,

You cannot cast a String to char. This will give you a compile time error. Why dont you make 'grade1' of type String instead of char. If for some reason you have to cast it from String to char type, than I would suggest using the toCharArray() method in the String class. The method will return you a new character array. Than by using some looping mechanism you can extract the required character and than apply your conditional constraints.
Alternately you could also use the charAt(int index) method of the String class to do the conversion, note that the first char value of the sequence is at index zero('0').
 
Garry Meax
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, if you know that the String contains only a single char for the grade, you can compare two String objects directly:


HTH

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic