the code below is from an assignment in my text book for a simple program that takes a user's entered name and capitalizes the first letter of the first and last name. The code works properly, but I do not understand why the name.substring() works correctly. Specifically, I am interested in how the block from lines 24 - 29 works. If the user enters the name "Johnny Johnson", then i should contain the value 7 going into line 29. If i does contain 7, then shouldn't name = name.substring(0, i) contain "Johnny J" which should make line 29 actually store "Johnny JJohnson" in String name? But instead it actually stores "Johnny Johnson" as it should.
My second question comes from messing around with this code to see different results. If I change the first part of line 29 to name = name.substring(0, i-1) I get the error (using Eclipse):
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15 at java.lang.String.charAt(String.java:558) at RepairName.main(RepairName.java:17)
Why does the error appear on line 17 instead of line 29? Actually, why do I get an error at all because i-1 isn't actually changing the value of i correct? I assumed it had something to do with the loop but since the value of i wasn't changed I didn't know why it would.
Sorry if this was a long-winded question. I'm new to Java and pretty new to programming (obviously), but I appreciate any insight you all can give. Thanks!
1 import javax.swing.*;
2
3 public class RepairName
4 {
5 public static void main(String[] args)
6 {
7 String name, saveOriginalName;
8 int stringLength;
9 int i;
10 char c;
11 name = JOptionPane.showInputDialog(null, "Please enter your first and last name");
12
13 saveOriginalName = name;
14 stringLength = name.length();
15 for (i = 0; i < stringLength; i++)
16 {
17 c = name.charAt(i);
18 if (i == 0)
19 {
20 c = Character.toUpperCase(c);
21 name = c + name.substring(1, stringLength);
22 }
23 else
24 if(name.charAt(i) == ' ')
25 {
26 i++;
27 c = name.charAt(i);
28 c = Character.toUpperCase(c);
29 name = name.substring(0, i) + c + name.substring(i+1, stringLength);
30 }
31 }
32 JOptionPane.showMessageDialog(null, "Original name was " + saveOriginalName + "\nRepaired name is " + name);
33 }
34
35 }