1

おそらくこれをカバーする質問がありますが、検索しても見つかりませんでした。アイデアは、次のような文字と行数のユーザー入力を指定してパターンを表示することです。

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

}

次に、ユーザーが「OK」を押すたびにこのパターンを繰り返し、「キャンセル」を押すと終了するようにする必要があります。文字列変数に蓄積することを理解できれば、それができると思います。助けてくれてありがとう。

4

4 に答える 4

0

高レベルのアプローチとして、これを試すことができます。StringBuilder2 つのインスタンスを作成します。lines目的のものがヒットするまでループします。反復ごとXに、最初StringBuilderに を追加してから、その内容全体をStringBuilder( 経由でtoString)\n改行に を付けて別の内容に追加します。そのループが終了したら、セパレーター用に 2 行の空行を追加します。次に、最初StringBuilderの文字が空になるまでループし、反復ごとに最後の char を削除し ( を介して)、 plusを介してdeleteCharAt(sb.length()-1)コンテンツ全体をもう一方の文字に再び追加します。完了すると、2 番目に希望するパターンが作成されます。StringBuildertoString\nStringBuilder

int lines = 4;
StringBuilder sb = new StringBuilder();

StringBuilder pattern = new StringBuilder();
for(int i = 0; i < lines; i++){
  sb.append("X");
  pattern.append(sb.toString() + "\n");
}
pattern.append("\n\n");
pattern.append(sb.toString() + "\n");
while(sb.length() > 0){
  sb.deleteCharAt(sb.length() - 1);
  pattern.append(sb.toString() + "\n");
}

System.out.println(pattern.toString());
于 2013-05-20T20:19:49.803 に答える
0

StringBuilder の使用が高度すぎる場合は、文字列を使用するだけで同じ効果を得ることができます。

String output1 = "";
for (i=1; i<=lines; i++) {
    for (n=1; n<=lines; n++) {
        output1 = output1.concat(n +"\n");
        // note the below commented out code should also work:
        //output1 = output1 + n + "\n";
    }
}

ただし、内部ループの反復ごとに新しい文字列が作成され、output1 に割り当てられるため、これは StringBuilder を使用する場合よりもはるかに効率的ではありません。

于 2013-05-20T20:47:29.230 に答える