1

I'm doings some beginners task in JAVA. With the help of FOR I'm going to create two simple triangles by just adding simple characters like * to a string like this:

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

and

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

I have done the first triangle with the code below, perhaps it could be done in some simplier/smarter way? But I'm not sure how to create the other triangle that starts with five * ?

public class Test {

public static void main(String[] args) {

String word = "";

        for (int x=1; x<5+1; x++){
        word += "*";

        System.out.println(word);

        }
}
}
1
  • How does your question title relate to your question body? Commented Sep 10, 2011 at 19:33

4 Answers 4

1

You can do the whole stuff without actually using String variables. Use one loop for every row and a nested loop for the number of asterisks in the current row. When you are at current row you have 6 - current asterisks. Sample code follows:

for (int row = 1; row <= 5; row++) {
   for (int i = 1; i <= 6 - row; i++) {
       System.out.print("*");
   }

   System.out.println();
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Oli - This site is for questions and answers. The OP showed some effort and I helped him. The question is not a gimme teh codez type. I think you are getting it too serious...
That's fair. But your answer would be better served by including some explanation. (I would remove the -1, but I can't until you edit your question again!)
0

You can create a "decrementing" loop counter like this:

for (int i = 5; i > 0; i--) {
    // Do something
}

Inside the loop, you could use another loop to create a string of i stars, and then print it.

Comments

0

Hint: Use the same string word, and ask for the substring(int,int). Remember to collect the return value to the old string itself. You need to a loop that runs until the length of string is 0.

Comments

0

One possibility would be to use the substring method to print part of a longer string:

public class Test {

    public static void main(String[] args) {

        String stars = "*****";

        for (int x=4; x>=0; x--){

             System.out.println(stars.substring(x));

        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.