2013-05-22 75 views
1

我想编写一个程序,输出一个像这样的钻石图案:打印钻石 - 无法输入输入?

* 
    *** 
***** 
    *** 
    * 

我试图通过先得到它打印钻石的上半部分开始。

我可以将'totalLines'输入到控制台中,但是当它提示'字符'时我不能输入任何内容。为什么会发生这种情况?

我们一直在使用JOptionPane来完成大部分的任务,所以我会遇到麻烦,但从我读的书中可以看出,这是正确的。

(如果你有时间和我谈的for循环,我敢肯定,他们需要工作,我会非常感激。)

public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

    int totalLines, lines, currLine = 1, spaces, maxSpaces, minSpaces, numCharacters, maxCharacters, minCharacters; 

    String character; 

    System.out.print("Enter the total number of lines: "); 
    totalLines = input.nextInt(); 
    System.out.print("Enter the character to be used: "); 
    character = input.nextLine(); 

    lines = ((totalLines + 1)/2); 
    // spaces = (Math.abs((totalLines + 1)/2)) - currLine; 
    maxSpaces = (totalLines + 1)/2 - 1; 
    minSpaces = 0; 
    // numCharacters = (totalLines - Math.abs((totalLines +1) - (2*currLine))); 
    maxCharacters = totalLines; 
    minCharacters = 1; 
    spaces = maxSpaces; 

    for (currLine = 1; currLine<=lines; currLine++) { 
     for (spaces = maxSpaces; spaces<=minSpaces; spaces--){ 
      System.out.print(" "); 
      } 
     for (numCharacters = minCharacters; numCharacters>= maxCharacters; numCharacters++){ 
      System.out.print(character); 
      System.out.print("\n"); 
     } 
     } 


    } 

回答

1

使用next()尝试,而不是nextLine()

+0

谢谢!这工作。 – Smeaux

+0

关于for-loops的任何建议? – Smeaux

+0

我添加了另一个解决'for'循环的问题。 –

0

我正在为您的for循环创建一个单独的答案。这应该非常接近你所需要的。

StringBuilder对您可能是新的。因为StringBuilder是可变的,并且String不是,所以如果您要对现有字符串进行多个级联,通常最好使用StringBuilder而不是String。您不必为此练习使用StringBuilder,但这是一个很好的习惯。

//Get user input here 
int lines = totalLines; 

if(totalLines % 2 != 0) 
    lines += 1; 

int i, j, k; 
for (i = lines; i > 0; i--) 
{ 
    StringBuilder spaces = new StringBuilder(); 
    for (j = 1; j < i; j++) 
    { 
     spaces.append(" "); 
    } 

    if (lines >= j * 2) 
    { 
     System.out.print(spaces); 
    } 

    for(k = lines; k >= j * 2; k--) 
    { 
     System.out.print(character); 
    } 

    if (lines >= j * 2) 
    { 
     System.out.println(); 
    } 
} 

for (i = 2; i <= lines; i++) 
{ 
    StringBuilder spaces = new StringBuilder(); 
    System.out.print(" "); 

    for (j = 2; j < i; j++) 
    { 
     spaces.append(" "); 
    } 

    if(lines >= j * 2) 
    { 
     System.out.print(spaces); 
    } 

    for (k = lines ; k >= j * 2; k--) 
    { 
     System.out.print(character); 
    } 

    if (lines >= j * 2) 
    { 
     System.out.println(); 
    } 
} 
+0

再次感谢您。我希望我明白我在代码中做错了什么,但我很感谢你的帮助。 – Smeaux