nexus_2006
nexus_2006

Reputation: 754

Better way to to use for loop?

This is my first real Java attempt, inside an android activity.

The code counts based on a starting point countStart and an ending point count1. I didn't include the entire class, but after the toString, it creates a textview and displays the string generated from the array (obviously I guess...)

It builds an array logically based on how many slots it will need, I didn't want to make the array too big because then a zero is output at the end.

Can someone tell me how to make this code more efficient? (fewer lines, less confusing, faster, less memory use)

//get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    //convert string to double
    double count1 = Double.parseDouble(message);
    //declare variables and arrays
    double[] countArray;
    double countStart = 3.5;
    //initialize array with exact number of elements needed
    countArray = new double[((int) (count1-countStart)) +1];

    //counts from countStart to count1 without going over count1
    for(double i=0; i<(((int) count1-countStart) + 1); i++) {
        if ((countStart+i)>count1) {
            break;
        } else {
            countArray[((int) i)] = countStart+i;
        }

    }

    //convert array to string
    String mensage = Arrays.toString(countArray);

Upvotes: 0

Views: 82

Answers (1)

alex
alex

Reputation: 6409

As a basic rule of thumb, anything you calculate something save it to a variable. That keeps things looks simpler and prevents the calculation from running multiple times.

double count1 = Double.parseDouble(message);
double countStart = 3.5;

int resultCount = (int)(count1 - countStart) + 1;
double results = new double[resultCount];

for(double i = 0; i < resultCount; ++i) {
    double result = countStart + i;
    if (result > count1) {
        break;
    } else {
        results[i] = result;
    }
}

Upvotes: 1

Related Questions