| Author |
Don't understand the purpose of charAt() and "" ..
|
WeiJie Lim
Ranch Hand
Joined: Sep 05, 2012
Posts: 68
|
|
For the above code, we have to use charAt(0) to get the character that is entered from sc.next() right ? Is it because the Scanner class do not have a method to grab char ?
For String details = ""; , what is the purpose of "" ? I removed them and there is a slew of errors..
Thanks in advance.
|
 |
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 5893
|
|
WeiJie Lim wrote:
For the above code, we have to use charAt(0) to get the character that is entered from sc.next() right ? Is it because the Scanner class do not have a method to grab char ?
You can answer that for yourself. Look at the docs for Scanner. Do you see a method there that returns the first character of the input stream?
For String details = ""; , what is the purpose of "" ? I removed them and there is a slew of errors..
Local variables do not have a value until you explicitly set one. So if you just do String details;, the details variable does not have any value.
Later, when we do details += ..., that says, "take the current value of 'details', and append something to the String object stored there." However, since details doesn't have a value (because we didn't give it one), that statement cannot succeed. We can't operate on the "current value" when there is no "current value."
The = "" part says that we are assigning to the "details" variable a reference value that points to an empty String object. That is, a String object that contains no characters. In the end, we're basically saying, "Here's an empty box. Now add this stuff to whatever is in the box."
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
WeiJie Lim wrote:For the above code, we have to use charAt(0) to get the character that is entered from sc.next() right ? Is it because the Scanner class do not have a method to grab char ?
Yes, but you could have answered that yourself by simply looking at the API documentation.
For String details = ""; , what is the purpose of "" ? I removed them and there is a slew of errors.
.
Doesn't surprise me. Look at the rest of the code. What is it doing?
That should help you understand why the String details = ""; is there.
Winston
[Edit] Too slow.
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
WeiJie Lim
Ranch Hand
Joined: Sep 05, 2012
Posts: 68
|
|
Oh okay, thanks alot.
I should be looking to the docs more often..
For the "" part, I didn't think of the fact that it is related to a local variable =/
Sorry.
|
 |
 |
|
|
subject: Don't understand the purpose of charAt() and "" ..
|
|
|