gpt4 book ai didi

Java:在字符串变量中累积输出模式?

转载 作者:行者123 更新时间:2023-12-01 04:40:26 27 4
gpt4 key购买 nike

可能有一个问题涵盖了这一点,但我在搜索中没有找到它。这个想法是根据用户输入的字符和行数显示一个模式,如下所示:

x
xx
xxx
xxxx

xxxx
xxx
xx
x

但我需要使用 JOptionPane 来执行此操作。这是我所拥有的:

import javax.swing.JOptionPane;

public class loopPattern {

public static void main(String[] args) {

String in, num, output1 = null, output2 = "";
int lines = 0;
int i, n = 1;

in = JOptionPane.showInputDialog("Please enter the character for the pattern:");
num = JOptionPane.showInputDialog("Please enter the number of lines in the pattern:");
lines = Integer.parseInt(num);

for (i=1; i<=lines; i++) {

for (n=1; n<=lines; n++) {

output1 = (n +"\n");
}
}

for (i=lines; i>=1; i--){

for (n=lines; n>=1; n--){
output2 = (n +"\n");
}
}

JOptionPane.showMessageDialog(null, output1 +output2);
}

}

每次用户点击“确定”时,我都必须让它重复此模式,并在点击“取消”时退出。我想如果我能弄清楚字符串变量中的累积,我就可以做到这一点。非常感谢您的帮助。

最佳答案

在字符串变量中累加称为 StringBuilder 。它允许您快速将内容附加到 StringBuilder 中,您可以从中调用 toString() 将其转换回字符串。

StringBuilder sb = new StringBuilder();
for (i=1; i<=lines; i++) {
for (n=1; n<=lines; n++) {
sb.append(n +"\n");
}
}

如果不能使用 StringBuilder,则使用 String 变量并使用“+”运算符将另一个字符串赋给它本身的值。这可以简写为“+=”

String string = new String();
string = string + "stuff to go on the string";
// or as a shorthand equivalent
string += "stuff to go on the string";

/// loop example
String myoutput = new String();
for (i=1; i<=lines; i++) {
for (n=1; n<=lines; n++) {
myoutput += n +"\n";
}
}

关于Java:在字符串变量中累积输出模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16657513/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com