Java, drawing a triangle using * symbols help

hybridxsv

Junior Member
Jan 18, 2011
5
0
0
So my assignment is to draw a triangle using the * symbol. The program will ask the user for a length input, which will be the height (number of lines).

___--*
__--* *
__-* * *
--* * * * (Example of length = 4, ignore the _ and -, just put those so that it looks more like a triangle)

I get that I will have to do a loop (while or for loops) using the length input and I have a basic idea of what to do but I can't quite figure out how to make the program write the * symbol a certain number of times (the input values). I can probably use some sort of a math equation (like int x = x - 1; in a loop) but how do I get the program to actually write that string (I just don't see how I can apply a math equation to a string).

Any help or hints would be great, thanks.
 
Last edited:

Leros

Lifer
Jul 11, 2004
21,867
7
81
Maybe this will help:

Code:
String s = "";

for(int i = 0; i < 10; i++) {
    s = s + " ";
}

System.out.print(s);

This should print out 10 spaces.
 

Monster_Munch

Senior member
Oct 19, 2010
873
1
0
You will probably want 2 loops, 1 nested inside the other.

Code:
int height = 4;
		
for (int i = 0; i < height; i++) {
   String line = "";
			
   for (int j = 0; j < i + 1; j++) {
      line = line + "*";
   }
			
   System.out.println(line);
}
 
Last edited:

Gooberlx2

Lifer
May 4, 2001
15,381
6
91
You will probably want 2 loops, 1 nested inside the other.

Code:
int height = 4;
		
for (int i = 0; i < height; i++) {
   String line = "";
			
   for (int j = 0; j < i + 1; j++) {
      line = line + "*";
   }
			
   System.out.println(line);
}

Assuming he needs the formatting, he'll need extra code to pad the left side of the string. There're a number of ways to do it. Here's one:
Code:
int h = 10;
for(int i=h; i>0; i--){
    //seed first *
    String line="*";
    //build rest of line String
    for(int j=0; j<(h-i); j++){
        line += " *";
    }
    //pad left side and print
[B]    System.out.println(String.format("&#37;1$#"+((h*2)-i)+"s", line));[/B]
}

or simpler (for me, since I rarely use formatting syntax):
Code:
int h = 10;
[B]char[] pad = new char[h];
Arrays.fill(pad, ' ');[/B]
for(int i=h; i>0; i--){
    blah blah blah
    //pad left side and print
    [B]System.out.println(new String(pad, 0, i-1) + line);[/B]
}

You could also just append space characters in another for loop, nested in the first.

edit: oh, and wrong forum. :p
 
Last edited:

hybridxsv

Junior Member
Jan 18, 2011
5
0
0
Thanks for the help and my bad about the wrong section. I finally got it to work.

Code:
for(int i=0; i<sides; i++){
     String triangle = "";
     int j = 0;

     System.out.print(new String(pad,0,i));
     
    while(j < height) {
        triangle = triangle + "* ";
        j++;
    }

    Triangles[i] = triangle;
    System.out.println(triangle);
    height--;
}

Enter the length of the side: 4
* * * * 
 * * * 
  * * 
   * 

A larger version looks like this:
* * * * * * * * * * * * * * * * 
 * * *   * * *   * * *   * * *   
  * *     * *     * *     * *     
   *       *       *       *       
    * * * * * * * * * * * * 
     * * *   * * *   * * *   
      * *     * *     * *     
       *       *       *       
        * * * * * * * * 
         * * *   * * *   
          * *     * *     
           *       *       
            * * * * 
             * * *   
              * *     
               *
 
Last edited:

Gooberlx2

Lifer
May 4, 2001
15,381
6
91
Out of curiosity, what does the rest of your code look like, where you're using arrays?

I added on to mine to output the same (though inverted from yours) pattern:

Code:
public static void main(String[] args) {
        // TODO code application logic here

        int h = 4;
        for(int row=0; row<h; row++){
            for(int i=0; i<h; i++){
                //seed first *
                String line="*";
                //build rest of line String
                for(int j=0; j<i; j++){
                    line += " *";
                }

                int leftPad = ((h*2)-(h-i));
                int rightPad = ((h*2)-1);
                line = String.format("%1$#"+leftPad+"s", line); //pad left
                line = String.format("%1$-"+rightPad+"s", line); //pad right

                //build full Line from concatenated strings                
                String fullLine = line;
                for(int k=0; k<row; k++){
                    fullLine += " "+line;
                }
                
                int a = (h*(h-row));
                int b = fullLine.length();
                int padLeft = fullLine.length() + (h*(h-(row+1)));
                fullLine = String.format("%1$#"+padLeft+"s", fullLine); //pad left
                System.out.println(fullLine);
            }
        }
    }

output:
Code:
compile:
run:
               *   
              * *  
             * * * 
            * * * *
           *       *   
          * *     * *  
         * * *   * * * 
        * * * * * * * *
       *       *       *   
      * *     * *     * *  
     * * *   * * *   * * * 
    * * * * * * * * * * * *
   *       *       *       *   
  * *     * *     * *     * *  
 * * *   * * *   * * *   * * * 
* * * * * * * * * * * * * * * *
BUILD SUCCESSFUL (total time: 0 seconds)
 
Last edited:

hybridxsv

Junior Member
Jan 18, 2011
5
0
0
I'm a very bad object oriented person I feel like so the code usually comes out quite messy unfortunately but here's what I did.

When I saw the assignment, the first thing I thought of was the bigger version just has multiple triangles of the simpler version, so I just decided to store that triangle and draw it however many times I needed to complete the triangle.

Code:
import java.util.*;

class Triangle {
    public static String[]Triangles;

    public void drawTriangle() {
        //This method writes out the menu and asks for the input value.
        //Then it calls two other methods, which draws the simple triangle
        //as well as the bigger version of the triangle.
        Triangle c = new Triangle();
        Scanner scan = new Scanner(System.in);
        int numSides;

        System.out.println("Welcome to the equilateral triangle drawing program.");
        System.out.print("Enter the length of the side: ");
        numSides = scan.nextInt();
        //Asks for the user input, variable set to numSides

        c.drawFirstTriangle(numSides);
        //Calls the method to draw simple triangle

        System.out.println("");
        System.out.println("A larger version looks like this:");

        c.drawSecondTriangle(numSides);
        //Calls the method to draw the bigger version of the triangle

    }

    public static void drawFirstTriangle(int sides) {
        int height = sides;
        char[] pad = new char[sides];
        Triangles = new String[sides];
        Arrays.fill(pad, ' ');
        //Initiating variables to be used within the class
        //Arrays.fill will occupy the pad array, putting a blank space char in it

        for(int i=0; i<sides; i++){
            String triangle = "";
            //Initiating triangle lines, initially set to blank.

            int j = 0;

            System.out.print(new String(pad,0,i));
            //Prints the spaces before the first * character is printed.
            //First run it will not print a space since i = 0, starting i = 1
            //this will print a blank space "i" number of times

            while(j < height) {
                triangle = triangle + "* ";
                j++;
            }

            Triangles[i] = triangle;
            System.out.println(triangle);
            //Once the string triangle is finished, it is stored in a array called Triangles

            height--;
        }
    }

    public static void drawSecondTriangle(int sides) {
        Triangle c = new Triangle();
        char[] pad = new char[sides*sides];
        Arrays.fill(pad, ' ');
        int height = 0, numCount = sides;
        //Initiating variables to be used within the class
        //Arrays.fill will occupy the pad array, putting a black space char in it
        //pad[] array's bound will be sides * sides since that's how many rows there will be

        for(int j = 0; j < sides; j++) {
            for(int i = 0; i < sides; i++) {
                int count = 0;
                String interSpaces = new String(pad,0,i*2);
                String spaces = new String(pad,0,height);
                //Initiating the two different spacings, one in the beggining
                //and the other for spacing in between the triangles

                System.out.print(spaces);

                while(count < numCount) {
                    System.out.print(Triangles[i]);
                    System.out.print(interSpaces);
                    count++;

                    //Prints out the first complete set of triangles
                    //Example: if length was 4, then it would print
                    //4 full triangles (the base)
                }

                System.out.println("");

                height++;
            }
            //Once the inner for loop is done, then it goes in the loop again to
            //build the next set of triangles, which will be 1 less triangle
            //then the previous set.
            numCount--;
        }
    }
    
    public static void main(String[]args) {
        //Initiates the Triangle class, and allows main method to call on other methods
        Triangle c = new Triangle();
        
        c.drawTriangle();
    }
}
 
Last edited:

Gooberlx2

Lifer
May 4, 2001
15,381
6
91
When I saw the assignment, the first thing I thought of was the bigger version just has multiple triangles of the simpler version, so I just decided to store that triangle and draw it however many times I needed to complete the triangle.

I think it's a good way to approach it, considering Java is certainly object oriented.