Computer Science Canada Assigning a string value to a char |
Author: | elmocookies [ Mon Jun 09, 2008 6:10 pm ] | ||||
Post subject: | Assigning a string value to a char | ||||
I've been trying to assign a string (consonantString) to a char (consonantChar). I found and tried using the following code:
Since the code assigns a char to a string, I tried changing it so it assigned a string to a char and I ended up with:
However, the to.Char() caused an error and the program said I should use toCharArray(); instead. When I tried that, it didn't work either. Does anyone know how I can fix that? Thanks in advance. |
Author: | OneOffDriveByPoster [ Mon Jun 09, 2008 6:15 pm ] |
Post subject: | Re: Assigning a string value to a char |
Strings can have multiple characters. In your case, constantString.charAt(0) is probably what you want. |
Author: | jeffgreco13 [ Tue Jun 10, 2008 8:01 am ] |
Post subject: | Re: Assigning a string value to a char |
wouldn't you have to declare the constantChar variable as an array? |
Author: | DemonWasp [ Fri Jun 13, 2008 9:22 am ] |
Post subject: | RE:Assigning a string value to a char |
As per http://java.sun.com/javase/6/docs/api/ , there IS no toChar() method in String. If you want a single character out of the string, then you should, as OneOff said, use charAt(index) instead. If you want the string as an array of characters, then you should use toCharArray(), which returns a char[] - so constantChar would have to be a char[], as jeffgreco said. You also don't need that (new String(existingString)).someMethod() nonsense. You can just use existingString.someMethod(). |