首页 > 解决方案 > 循环只在文本字段中打印一次,但在系统打印中工作得很好

问题描述

我想创建一个列出电源并在用户输入时停止的程序。当我输入文本然后在系统中的 for 循环时,它应该如何工作,但是当我尝试在 textfeild 中运行相同的代码时,它只打印用户输入的数字。

int n;
n= Integer.parseInt(txtExponent.getText());
for (int i= 0; i <= n; i++) {
txtOutput.setText ("to the power of " +i);
}

它输出“用户输入的任何内容的幂,而不是 1 的幂,2 的幂等,直到它到达用户输入

标签: javafor-loop

解决方案


将预期输出的每一行附加到 aStringBuildertxtOutput在循环终止后将其设置为。

int n;
n = Integer.parseInt(txtExponent.getText());
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= n; i++) {
    sb.append("to the power of " + i).append(System.lineSeparator());
}

txtOutput.setText(sb.toString());

推荐阅读