PDA

View Full Version : "for" statement



logical
02-19-2012, 12:02 AM
This probably has a very simple answer but i can't seem to find it...

How do I do this in java (c++ syntax i think):

for( i = 0, j = 100; i < arr.length && j > 30; i++, j--){
Thanks in advance :P

Method
02-19-2012, 12:10 AM
Assuming you've declared i, j, and arr, that piece of code should work just fine.

logical
02-19-2012, 12:15 AM
really?

here's the snippet.. (it makes an increasing array from one number to the next)
public static int[] make(int from, int to){
int[] arr = new int[Math.abs(from - to)];
int low = to > from ? from : to;
int hi = to < from ? from : to;
int upOrDown = to > from ? 1 : -1;
for (int j = 0, int i = low; j < arr.length && i < hi; j++, i + upOrDown){
arr[j] = i;
}
return arr;
}

it gives me this error when i mouse over the "for" line:
<identifier> expected

'.class' expected

')' expected

> expected

not a statement

> expecte...

I'm using Netbeans IDE btw...

Method
02-19-2012, 02:27 AM
When you're declaring multiple variables of the same type on the same line, you only include the type of the first variable. You'll want to remove the "int" before "i = low" in that piece of code.

Also, "i + upOrDown" doesn't modify i. You might be looking for "i = i + upOrDown", or "i += upOrDown" for short.

logical
02-19-2012, 12:37 PM
Ty Method :D!

just for the record here is the final function

public static int[] make(int from, int to){
int[] arr = new int[Math.abs(from - to) + 1];
int inc = to > from ? 1 : -1;
for (int j = 0, i = from; j < arr.length; j++, i += inc){
arr[j] = i;
}
return arr;
}