I'm new to Java, and I'm trying to format an equation with int elements in an array (I keep getting the error "not a statement"). This is the bit of code:
int n = 0;
int[] time = {mins, mins2, mins3, mins4, mins5};
for(int j = 0; j <= 3; j++){
if (time[j] < time[j+1]){
n = time[j];
}
}
for(int k = 0; k <= 4; k++){
time[k] - n;
}
I found the smallest int (all elements are from a random number generator), and now I want to subtract the smallest from every element and permanently change the elements of the given array to those smaller numbers. I don't know how to format the "time[k] - n;" segment correctly.
Thank you for your help.
The line:
Does nothing. It takes the value
time[k]
and subtracts the valuen
from it. It then discards the result.What you want is to subtract
n
from the variable and assign the result back to the same variable:In Java, this is equivalent to a compound assignment operator:
If you have Java 8 you could in fact do:
And even with earlier versions of Java I would recommend:
i.e. use a foreach loop where you can and otherwise use the
length
property of the array rather than hardcoding the length.