Page 1 of 1
how do i use a forloop to increment array indices? In Java
Posted: Sat Oct 16, 2004 11:15 pm
by Darktalyn1
i have a character array with 4 indices called
char[] pegs = new char[4];
i want to use a for loop that will go through and perform the same action on each of the indices
however when i type
for(pegs = 0; pegs <=3; pegs++){
//all the code goes in here
}
it tells me that im using incompatible types. So, i realize I'm not that much of a coder ... i guess i can see why it's not working - it's a character array, not int. The question is ... how do i do it then?!
Thanks in advance
Posted: Sat Oct 16, 2004 11:21 pm
by fliptw
why do you want to use chars arrays? Java does have a String object you know.
anyways, you can't increments arrays, which is what pegs++ is doing, but pegs[i++](where i is an int), incrementing the
index of the array is perfectly legal.
something like:
Code: Select all
for(int i =0; i<=3; i++){
pegs[i]='l';
...
}
read thru the API documentation, you'll lots of nifty stuff.
Posted: Sat Oct 16, 2004 11:22 pm
by Grendel
Pegs is your pointer to the data -- you need an index variabl like
cahr[] pegs = new char[4] ;
for ( int i = 0 ; i <=3 ; ++i )
{
pegs = ... ;
}
Note: the for ( int i .. is C++ syntax dunno if java will do it. Split it out of the for if not.
Posted: Sat Oct 16, 2004 11:33 pm
by DCrazy
Grendel, Java's Array objects are not the same thing as C/C++ arrays, in that they are not pointers to blocks of memory. They are actual objects (Java.lang.Array). Java will do the int i = 0; in the for loop, but I'm not entirely sure that it has the prefix increment operator (++i). Just as valid to use i++ anyway.
Posted: Sun Oct 17, 2004 9:53 am
by Darktalyn1
Hey thanks guys you're right. that did work ! Now I just have to figure out how to use the forloop with a modulo operator...
Posted: Sun Oct 17, 2004 1:24 pm
by fliptw
the modulus operator returns the remainder of the division of two integers. so 5 % 2 would return 1, and 4 % 2 would return 0.
you are pretty much walking thru each of the indexes of the pegsMatched array, so you can condense those three blocks of code into one loop.
Posted: Sun Oct 17, 2004 2:08 pm
by DCrazy
This is one of those Mastermind games, isn't it? You have to guess a code of four colored pegs, and it tells you which ones are in the right spot, which ones are out of place, and which ones aren't even in the code?