I'm dumb. Help me.

Post » Sun Sep 30, 2012 2:26 am

Get in here, coders! All here? Okay, so:

I've started teaching myself Java for kicks, and I've been doing some exercises I found online, and there's something I'm a bit confused about.

"January".substring(0,3)

This returns "Jan", right? But if "J" is 0, and "N" is 3, what is "A"? Is "A" 2? What happened to 1? I don't understand.

Another example:

"Hello".substring(0,2)

This returns "He". Why??? Where is 1?
User avatar
Devin Sluis
 
Posts: 3389
Joined: Wed Oct 24, 2007 4:22 am

Post » Sun Sep 30, 2012 1:28 pm

(0, 3) returns everything up to but not including the character at the 3rd index. That's how range works in Python, anyway. That would explain why (0,2) only gives the characters at 0 and 1.

Also, in January, J is 0, a is 1, and n is 2.
User avatar
remi lasisi
 
Posts: 3307
Joined: Sun Jul 02, 2006 2:26 pm

Post » Sun Sep 30, 2012 1:19 pm

In Java, the substring function works as follows:

The first parameter is the starting point. The second parameter is the number of characters, call it n.

Remember that arrays and strings are indexed starting at 0. n + SP - 1 = endPos or the length of the string - 1 (for the last character), whichever is lower.
User avatar
Hairul Hafis
 
Posts: 3516
Joined: Mon Oct 29, 2007 12:22 am

Post » Sun Sep 30, 2012 9:11 am

(0, 3) returns everything up to but not including the character at the 3rd index. That's how range works in Python, anyway. That would explain why (0,2) only gives the characters at 0 and 1.

Also, in January, J is 0, a is 1, and n is 2.

Okay ... Y is "up to but excluding". Yay! I got it. Awesome, thanks for explaining this so simply.

The first parameter is the starting point. The second parameter is the number of characters, call it n.

Remember that arrays and strings are indexed starting at 0. n + SP - 1 = endPos or the length of the string - 1 (for the last character), whichever is lower.

This took a bit more understanding, but I get it. Okay.

Thanks, coders! /end

P.S. Sorry for the almost spam. I tried to find the answer online, but there doesn't really seem to be much in the way of succinct explanations.
User avatar
ONLY ME!!!!
 
Posts: 3479
Joined: Tue Aug 28, 2007 12:16 pm

Post » Sat Sep 29, 2012 9:14 pm

This took a bit more understanding, but I get it. Okay.

Sorry, my brain works in terms of mathematical equations. :P
User avatar
Damned_Queen
 
Posts: 3425
Joined: Fri Apr 20, 2007 5:18 pm


Return to Othor Games