Reputation: 71
I'm trying to write a program that outputs a diamond pattern like this:
*
***
*****
***
*
I've started by trying to first get it to print the top half of the diamond.
I can input the 'totalLines' into the console, but I can't type anything when it prompts for 'character'. Why would this be happening?
We've been using JOptionPane for most of our assignments, so it makes sense that I'd be having trouble with this, but from what I can tell from reading the book, this is correct.
(And if you have time to talk to me about the for-loops, I'm pretty sure they need work. I'd be very grateful.)
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");
}
}
}
Upvotes: 1
Views: 573
Reputation: 2660
I'm creating a separate answer in regards to your for
loops. This should be pretty close to what you need.
StringBuilder
might be new to you. Because StringBuilder
is mutable and String
is not, if you're doing multiple concatenations onto an existing string it's usually preferable to use StringBuilder
instead of String
. You don't have to use StringBuilder
for this exercise but it's a good habit to start.
//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();
}
}
Upvotes: 0