java - 循环只在文本字段中打印一次,但在系统打印中工作得很好
问题描述
我想创建一个列出电源并在用户输入时停止的程序。当我输入文本然后在系统中的 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 的幂等,直到它到达用户输入
解决方案
将预期输出的每一行附加到 aStringBuilder
并txtOutput
在循环终止后将其设置为。
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());
推荐阅读
- go - InvalidClientTokenId:请求中包含的安全令牌无效
- ruby-on-rails - 如何在模块内调用路由助手?
- css - 粘性顶部不适用于 Angular8/safari
- php - 在 Symfony 5 中使用属性制作表格
- perl - 如何将 Data::Dumper 和 Statistics::Diversity::Shannon 组合成一个完整的循环?
- gtk - 如何使用菜单按钮 (Gtkmm)
- javascript - 添加导入后,我的 chrome 扩展程序立即停止工作
- javascript - React - 从 JSON 响应动态设置 backgroundImage
- c++ - 当引用的变量从外部更改时,使用对 const 的引用是否安全?
- javascript - React Hooks:Hooks 只能在函数组件内部调用