Print elements of a For loop in AndroidStudio [closed]

2

I have created a program that receives the elements of an arithmetic progression (First term, ratio and number of terms) and returns all the terms of the progression and the sum of those terms. The sum shows it well, but when I want to see all the terms it only shows me the last one.

Here is my code. As I said, everything works fine, the only thing that does not work out is that all the terms of the progression are shown:

public void mostrarProgresion(View view){
    asignarDatos();
    //n1=Primer Término
    //n2=Razón
    //n3=Número de Términos
    total=n2*n3;
    if (n1>=n3){
        total+=n1;
    }
    for (int i=n1;i<total;i=i+n2){
        txvres.setText(i);
    }
}
    
asked by Franco Zaconetta Gosicha 26.04.2017 в 04:00
source

2 answers

3

The problem is here:

for (int i=n1;i<total;i=i+n2){
    txvres.setText(i);
}

With setText you indicate the text that is going to be displayed, and just as you are doing, in each pass you update the loop to the next term. Then when the loop ends, you have shown and overwritten all the terms leaving only the last as visible. It is not that I show you only the last term, it has shown them all and has overwritten them all.

If what you want is to show them all at the same time, what you could do is read the text (for example with getText ) and concatenate the new value at the end (EYE because I have not used Android Studio in a lot time and I have not tried it and probably contains errors):

for (int i=n1;i<total;i=i+n2){
    txvres.setText( txvres.getText() + ", " + i );
}
    
answered by 26.04.2017 / 08:10
source
1

What @AlvaroMontoro says is totally true, you are showing each term in each iteration but you are overwriting it. An alternative that Alvaro tells you about could be the following in which you are concatenating all the terms in string and then show them all at the same time:

String terminos = "";

for (int i=n1;i<total;i=i+n2){
    terminos += ", " + i;
}

txvres.setText(terminos);
    
answered by 26.04.2017 в 09:41