2015-10-28 66 views
-4
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); 
}} 
+0

它不是沃金正确,请帮助 – Waseem

+0

什么工作不正常?你在期待什么? – Kai

+0

* ** *** **** ***** 我想要金字塔星 – Waseem

回答

0

您需要多个循环到另一条线路显示文本。

不要使用字符串连接来建立你的字符串。

喜欢的东西:

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 
0

我想这是你想要什么:

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