2014-02-09 105 views
-2

我需要编写一个程序,给定一个数字和一个字母,它将打印该字母的次数与给定的数字。之后,我需要调用第一个方法并使用给定的值创建一个三角形。 第一个输出应该是这样的,如果我给它的参数(5,“u”)=“uuuuu” 我已经有了第一部分,但我需要调用第一个方法并获得像这样的输出:我需要做一个倒三角形

u 

    uu 

    uuu 

uuuu 

uuuuu 

这是我到目前为止的代码:

public class Triangle 
{ 

    private String theLetter; 
    private int cnt; 
    private String aLetter; 
    private int howMany; 

    public void getLetters(int cnt, String theLetter) 
    { 
     System.out.print("\""); 
     for(int x=0; x < cnt; x++) 
     { 
      System.out.print(theLetter); 
     } 
     System.out.print("\""); 
     System.out.println(); 
    } 

    public void getLetterTriangle(int howMany, String aLetter) 
    { 
     for(int i = 0; i < howMany ; i++) 
     { 
      getLetters(howMany, aLetter); 
     } 
      System.out.println(); 
    } 
} 

我只是不能在for循环做到这一点。请帮助。

+0

请澄清的问题是什么。 – Vitruvius

+0

问题是我无法做for循环来获取三角形的形状,但有人已经向我展示了代码,但是非常感谢@Saposhiente – Dylan

回答

-1

在getLetters改变你的代码:

public void getLetters(int cnt, int howMany, String theLetter) 
{ 
    System.out.print("\""); 
    for(int x=0; x < (howMany-cnt); x++) // you need to display spaces 
     System.out.print(" "); 
    for(int x=0; x < cnt; x++) 
     System.out.print(theLetter); 
    System.out.print("\""); 
    System.out.println(); 
} 

和getLetterTriangle

public void getLetterTriangle(int howMany, String aLetter) 
{ 
    for(int i = 1; i <= howMany ; i++) // start with 1 
     getLetters(i, howMany, aLetter); // display i, total width howMany 
} 
+1

-1:这是作业。不要破坏。不要给出明码。至少给一个非常彻底的解释。 –

+0

@MartijnCourteaux我已经对每个更改过的部分发表了评论,他们足以了解问题所在 –

+0

感谢您的帮助@Lashane – Dylan

1

你应该看看这部分:

for(int i = 0; i < howMany ; i++) 
{ 
    getLetters(howMany, aLetter); 
} 

如果你仔细观察,你会发现,在循环中不断变化的变量是i,不howMany。由于这显然是一项家庭作业,我将其余的留给你。

更新:你也应该看看Martijn Courteaux的答案。他对前面的空间有一个有效的观点。

+0

我知道问题出在那里。我不知道如何让for循环来完成它。我试图去做,但我无法得到它。我甚至问过我的一些朋友,但依然如此。我知道我需要自己去尝试,但是我还是得不到一些东西,因为我们在课堂上看到的信息不足。不过谢谢你。 – Dylan

+0

尽量在上课之前了解Lashane的代码。真的,你所能做的最好的事情就是坐下来思考代码是一行一行的。您也可以使用调试器来跟踪真实的程序流程和变量的值。 – luksch

1

您正在打印一个正方形。在您的getLetters()方法中,您应该有两个部分。第一部分应打印空格,第二部分应打印该字母。您需要使用getLetters()方法的额外参数,以便在打印字母之前知道需要打印多少个空格。