首页 > 解决方案 > 我正在尝试创建一个新行但它不起作用

问题描述

int exponent = Integer.parseInt(txtExponent.getText());
int base = Integer.parseInt(txtBase.getText());
int n = Integer.parseInt(txtExponent.getText());
StringBuilder sb = new StringBuilder();

for (int i = 1; i <= n; i++) {
    sb.append( base + " to the power of " + i + "=" + "\n") //no new line
        .append(System.lineSeparator());
}

我正在尝试为每个新循环创建一个新行,例如 3 次方新行到 4 次方。但它不起作用。

input txtOutput.settext (sb)

预期输出:

-to the power of 4= 
-to the power of 5= 
-to the power of 6=
etc

实际输出:

to the power 4= to the power of 5= to the power of 6=

标签: javaloopsnewline

解决方案


确实有新行,如下面的 jshell 所示(在我的例子中,即使没有添加 System.lineSeparator()):

jshell> int n = 3
n ==> 3

jshell> int base = 2
base ==> 2

jshell> StringBuilder sb = new StringBuilder()
sb ==> 

jshell> for (int i = 1; i<= n; i++) sb.append(base + " to " + i + "=" + "\n");

jshell> sb.toString()
$12 ==> "2 to 1=\n2 to 2=\n2 to 3=\n"

jshell> System.out.print(sb.toString())
2 to 1=
2 to 2=
2 to 3=

推荐阅读