Search code examples
javastringfor-loopdesign-patternsjoptionpane

Java: Accumulate output pattern in string variable?


There is probably a question that covers this, but I haven't found it in searching. The idea is to display a pattern given user input for the character and number of lines like this:

x
xx
xxx
xxxx

xxxx
xxx
xx
x

But I need to use JOptionPane to do this. Here is what I have:

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);
    }

}

I have to then make it repeat this pattern each time the user hits "Ok" and quit when they hit "Cancel". I think I can do that if I could just figure out the accumulating in a string variable thing. Thanks so much for the help.


Solution

  • Accumulating in a string variable is called a StringBuilder. It allows you to quickly append things into the StringBuilder from which you can call toString() to transform it back to a String.

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

    if you can not use a StringBuilder, then use a String variable and assign it the value of itself with another string using the "+" operator. This can be shorthanded with "+="

    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";
        }
    }