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

标签 java string for-loop design-patterns joptionpane

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

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/

相关文章:

java - JEdi​​torPane - 切换回默认编辑器工具包

java - 用 Java 读取大文件

Java 2D数组,可以设置单独的大小吗?

java - 使用 libgdx 时字符串固定在屏幕上

c++ - 无法将 CStringW 转换为 CStringA

iphone - 如何停止 for 循环并执行另一个方法,然后返回继续执行 Objective-C?

java - 如何对 HashMap 进行降序排序(基于值)并同时保持字典顺序(基于键)?

regex - Grep模式匹配用双引号括起来的小写字符串

javascript 循环中的闭包

c++ - 是否可以仅使用循环在形状内绘制形状?如果是这样,请指出正确的方向