Skip to content Skip to sidebar Skip to footer

How To Display Each Value In Turn From A For Loop

This program gives one value of Htm for each value of i. I want to display each value in turn by repeatedly pressing the calculate button. I want it to display the values for i=0 a

Solution 1:

As far as I understand from your question, you should not use your for loop

for (i = 0; i <= 11; i++)

Remove this for loop, Declare a variable, and set "i" to it, when exiting onClick increase your variable.

privateint counter=0;

publicvoidonClick(View v){
    int i=counter;
    //everything continues, just remove the for loop
    angle.setText("Beta =" + ang);
    counter++;
    if(counter==12) counter=0;//your arrays are fixed, so we are turning back
}

Solution 2:

Simply remove your current loop, since you call break after one iteration anyways:

for (i = 0; i <= 11; i++) {

Then make i a field variable and increment it each time you press the Button:

privateinti=0;

@OverridepublicvoidonClick(View v) {
    // Do all your calculations and call setText() like above...

    i++;
    if(i == Hm.length)  // Start over 
        i = 0;
}

(This assumes that every Array is equal to or larger than Hm... which is dangerous. You should perform more thorough checks.)

Solution 3:

How do you want to display them? Just tacking them on to a TextView's string?

textView.setText(someString);

A ListView of TextView's each representing a new calculation?

privateList<String> mCalculations = newLinkedList<String>();

privateAdapter mAdapter;

@OverridepubliconCreate(Bundle instance) {
    mAdapter = newArrayAdapter(getContext(), android.R.layout.simple_list_item_1, mCalculations);
    ((ListView) findViewById(R.id.my_list_view)).setAdapter(mAdapter);
}

@OverridepublicvoidonClick(View v) {
    newAsyncTask<Void, Void, Double>() {
        publicDoubledoInBackground(Void... values) {
            /* perform calculation */return value;
        }

        publicvoidonPostExecute(Double... values) {
            if(values.length <= 0) return;
            String text = String.valueOf(values[0]);
            mCalculations.add(String.valueOf(value));
            mAdapter.notifyDataSetChanged();
        }
    }.execute();
}

Solution 4:

Don't use a for loop, instead create a global variable i and increase it each time you click the button

Solution 5:

Under you onClick you start with a for loop

    for (i = 0; i <= 11; i++) {

this is setting i to start at zero every time you click the button. Then at the end of your loop you use break to break out of the loop. This is making this loop useless and you do not need a loop for this part.

in your initialize function you should set i equal to zero. Then in your onClick function take out the first for loop and where you have break, take that out and replace it with i++.

Post a Comment for "How To Display Each Value In Turn From A For Loop"