Formatting equations?

164 views Asked by At

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.

2

There are 2 answers

1
Boris the Spider On

The line:

time[k] - n

Does nothing. It takes the value time[k] and subtracts the value n 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:

time[k] = time[k] - n

In Java, this is equivalent to a compound assignment operator:

time[k] -= n

If you have Java 8 you could in fact do:

int[] time = {mins, mins2, mins3, mins4, mins5};
int min = IntStream.of(time).min().getAsInt();
int[] normalised = IntStream.of(time).map(i -> i - min).toArray();

And even with earlier versions of Java I would recommend:

int[] time = {mins, mins2, mins3, mins4, mins5};
int n = Integer.MAX_VALUE;
for (int t : time) {
    n = Math.min(n, t);
}
for (int i = 0; i < time.length; ++i) {
    time[i] -= n;
}

i.e. use a foreach loop where you can and otherwise use the length property of the array rather than hardcoding the length.

0
Jens On

Change time[k] - n; to time[k] =- n;. So it will store time[k] - n in time[k]