我正在尝试编写一个输出菱形图案的程序:
*
***
*****
***
*
我开始尝试首先打印出钻石的上半部分。
我可以在控制台中输入'totalLines',但在提示输入'character'时我无法输入任何内容。为什么会发生这种情况?
我们一直在使用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");
}
}
}
答案 0 :(得分:1)
尝试使用next()
代替nextLine()
。
答案 1 :(得分: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();
}
}