Why won't this work as expected!?

for(int i=0;i<Nname.length;i++){

if(i><Nname.length){

System.out.print(Nname[i]+", ");

}

if(i == Nname.length){

System.out.print(Nname[i]);

}

}

Basically what I need is to display the Nname variable as many times as needed... BUT, I only want to show a comma until before the last iteration of the for loop ... so the last one is not shown with a comma... the thing is that for some reason... it does not work. Any pointers!?>

[807 byte] By [Elvenelfa] at [2007-11-27 9:58:10]
# 1
i will never == Nname.length. on the last trip through the loop, it will == Nname.length - 1. THAT is what you need to check for.
petes1234a at 2007-7-13 0:28:37 > top of Java-index,Java Essentials,New To Java...
# 2
Why?i starts from 0... and there are 6... hmmm the length doesnt start from zero count!? that should be it...
Elvenelfa at 2007-7-13 0:28:37 > top of Java-index,Java Essentials,New To Java...
# 3

To see this visually, in this small bit of code:

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

{

System.out.println(i);

}

what is the last number printed? It's not 5 is it? So if you want to trap for the last trip through the loop, and if you are using a < condition as the final condition (not <= ), then you will need to trap for LoopMax - 1.

petes1234a at 2007-7-13 0:28:37 > top of Java-index,Java Essentials,New To Java...
# 4

what happens when i == Nname.length? does the loop run? nope because it will only run when i is less than Nname.length.

By the way, as an unrelated aside, if you want to follow java naming conventions, don't name your array var Nname. It should start with a lower case letter. nName would be better.

Message was edited by:

petes1234

petes1234a at 2007-7-13 0:28:37 > top of Java-index,Java Essentials,New To Java...
# 5
Ah, I see now. Thanks a lot pete! Man youre getting all my "duke stars" LOL
Elvenelfa at 2007-7-13 0:28:37 > top of Java-index,Java Essentials,New To Java...
# 6

Thanks so much... this is my final code:

for(int i=0;i<Nname.length;i++){

if(i==Nname.length-1){

System.out.print(Nname[i]);

}else{

System.out.print(Nname[i]+", ");

}

Following your edit: Ok, I will change that asap. Thanks so much once more!

Message was edited by:

Elvenelf>

Elvenelfa at 2007-7-13 0:28:37 > top of Java-index,Java Essentials,New To Java...