• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Don't understand the purpose of charAt() and "" ..

 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10509
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic