簡體   English   中英

在 JOptionPane.showMessageDialog 中打印星星?

[英]print stars in JOptionPane.showMessageDialog?

import javax.swing.*;

class A1{
  public static void main(String args[]) {

  String z= "";
  String a = JOptionPane.showInputDialog(null,"Enter no");

  int b = Integer.parseInt(a);
  for (int i = 1 ;i <=b ; i++){
  z +=  "*" ;}

  JOptionPane.showMessageDialog(null,"\n"+z);
}}

您將需要多個循環才能在不同的行上顯示文本。

不要使用字符串連接來構建您的字符串。

就像是:

String a = JOptionPane.showInputDialog(null,"Enter no");

int b = Integer.parseInt(a);

StringBuilder sb = new StringBuilder();

for (int i = 0 ; i < b ; i++)
{
    for (int j = 0; j < i; j++)
    {
        sb.append( "*" );
    }

    sb.append("\n");
}

JOptionPane.showMessageDialog(null, sb.toString());

請注意,此代碼無法正常工作。 我會讓你解決索引范圍的問題。

另一種選擇是使用 JTextArea 在 JOptionPane 中顯示您的輸出,那么您的邏輯將只需要一個循環。

在這種情況下,代碼將類似於:

JTextArea textArea = new JTextArea(b, b);
StringBuilder sb = new StringBuilder();

for (int i = 0 ;i <b ; i++)
{
    sb.append("*");
    textArea.append(sb.toString());
    textArea.append("\n");
}

JOptionPane.showMessageDialog(null, textArea); // not sure if 

我想這就是你想要的:

        for (int i = 1; i <= b; i++)
        {
            for (int y = 1; y <= i; y++)
                z += "*";
            z += "\n";
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM