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


    }
4

2 回答 2

1

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

于 2013-05-22T00:03:09.837 回答
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();
    }
}
于 2013-05-22T01:56:59.013 回答