简体   繁体   中英

How to Print Multiple Statements to One TextView

I have the following code:

for(int i = 1; i <= doubleLength; i++) {
    doubleRate = (doubleBalance * (doubleRate/100))/12;
    doubleBalance = doubleBalance + doubleRate;
    doublePayment = (doubleBalance/doubleCount);

    TextView results = (TextView) findViewById(R.id.showResult);
    results.setText(doublePayment+"");

    doubleCount = doubleCount - 1;
    doubleBalance -= doublePayment;
}

What I'm trying to do is print out every single value of the "doublePayment" value to a TextView UI Object on the screen. However, when the for loop finishes, it only prints out one value, instead of several.

I'm porting this over from C++, so I'm used to simply using cout to print to the terminal.

The problem is here:

results.setText(doublePayment+"");

You're re setting the text value instead of appending the whole String. A better approach would be using a StringBuilder :

StringBuilder sb = new StringBuilder();
for(int i = 1; i <= doubleLength; i++) {
    doubleRate = (doubleBalance * (doubleRate/100))/12;
    doubleBalance = doubleBalance + doubleRate;
    doublePayment = (doubleBalance/doubleCount);

    sb.append(doublePayment);
    sb.append(" ");

    doubleCount = doubleCount - 1;
    doubleBalance -= doublePayment;
}
TextView results = (TextView) findViewById(R.id.showResult);
results.setText(sb.toString());

As Raghunandan suggests you do not need to initialize textview inside the loop. Move

TextView results = (TextView) findViewById(R.id.showResult);  

outside the loop.

And instead of setText use append

results.append(doublePayment+"\n");

Try this

 results.setText(results.getText().toString() +  ", " +doublePayment);

For better performance use a StringBuilder .

String res = new StringBuilder(results.getText().toString())
    .append(", ")
    .append(doublePayment)
    .toString();

results.setText(res);

You need to build the text first (in a StringBuilder or whatever), then do the setText outside the loop.

Alternately, you can do

results.setText(results.getText().toString() + System.getProperty("line.separator") + doublePayment);

if you don't want it outside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM