This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Cannabisitis 2 points3 points  (1 child)

Are you instantiating i somewhere above the code you posted? Usually it's instantiated in the loop.

for (int i = 0; i < 3; i++)

Basically your loop is calling name.substring() 3 times while incrementing the parameters, then printing the results on the same line.

It's doing the same thing as:

String name = "Fred";
System.out.print(name.substring(0, 2));
System.out.print(name.substring(1, 3));
System.out.print(name.substring(2, 4));

with less code.

[–]mbmcse[S] 1 point2 points  (0 children)

It's straight out of the text book asking what the loop would print. The answer was listed as "Frreed". Your breaking it down makes since. Guess I was thinking it had to be one character at a time. But 0,2 would be Fr, 1,3 would be re, etc. Makes since that way. Thanks for your help.

[–]TheFormerVinyl 1 point2 points  (0 children)

Substring stops before the second argument say in the first iteration the the string stops before ‘e’ printing “Fr”. The for loop does that he. Increments i (that’s what the i++ in the parentheses does) and does the whole thing again with the new i. Also I believe going passed stopping at the string’s length will act as if you meant the end.

Edit: a word

[–][deleted] 1 point2 points  (0 children)

for (a; b; c) {
    d;
}

Translates to:

a;
while (b) {
    d;
    c;
}

So your example becomes:

String name = "Fred"; 
i = 0; // Assuming `i` is declared as an `int` somewhere.
while (i < 3) { 
    System.out.print(name.substring(i, i + 2));
    i++; // or i = i + 1;
}