0

This is a homework question so I would like help, not an answer.

I'm trying to create 2 triangles out of numbers based on a number entered by the user.

"Enter a number between 2-9: "3"
1
12
123

  1
 21
321

IE2:

"Enter a number between 2-9: "5"
1
12
123
1234
12345

    1
   21
  321
 4321
54321

I have been able to get the first triangle complete. But when I add my nested loop it messes up my first triangle with the numbers developed from the nested loop. It also puts all the numbers in a straight vertical line. I've tried variations for different nest loops and even tried messing with a StringBuilder, but was still unsuccessful. Here's what I have in code so far:

import java.util.Scanner;

public class NestedLoops
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a Number between 2-9: ");
        int width = input.nextInt();

        String r = "";
        for (int i = 1; i <= width; i++)
        {
            r = r + i;
            System.out.println(r);

        }

    }

}

Again, I'm looking for help/understanding and not just an answer.

13
  • Please hover over the homework tag and read what it says there. Commented Feb 17, 2013 at 3:30
  • do you need to use a nested loop for the assignment? You can solve this in two loops without nesting them or even 1 with some more complicated string manipulation. Commented Feb 17, 2013 at 3:32
  • @Xymostech, can't use school. suggestions? Commented Feb 17, 2013 at 3:32
  • Thought of using printf ?? Commented Feb 17, 2013 at 3:33
  • @RayCheng What do you mean? Commented Feb 17, 2013 at 3:33

6 Answers 6

1

There are two aspects the 2nd part of the question.

  1. You need to generate strings with the numbers in the reverse order:

    • You could do this by adding the numbers at the other end.
    • You could do this by reversing the strings.
  2. You need to arrange that there are spaces to the left.

    • You could do this by adding the required number of spaces to the left end of the string.
    • You could do this by using the System.out.format(...) with a template that right aligns the string in a field with the required number of characters. (OK, that's a bit too obscure ...)

Or, you can build the string in a character array or string builder rather than using string concatenation.

The "trick" is to figure out what strategy you are going to use ... before you start cutting code.

Sign up to request clarification or add additional context in comments.

Comments

0

try

    int width = 5;
    // for all lines; number of lines = width
    for (int line = 1; line <= width; line++) {
        // print numbers from 1 to current line number  
        for (int n = 1; n <= line; n++) {
            System.out.print(n);
        }
        // end of line
        System.out.println();
    }
    // add empty line between triangles
    System.out.println();
    // for all lines; number of lines = width
    for (int line = 1; line <= width; line++) {
        // printing padding spaces, number of spaces = with - line number
        int nSpaces = width - line;
        for (int i = 0; i < nSpaces; i++) {
            System.out.print(" ");
        }
        // print numbers from number of current line to 1
        for (int n = line; n >= 1; n--) {
            System.out.print(n);
        }
        // end of line
        System.out.println();
    }

2 Comments

Please disregard my last comment, I didn't see where you set line back to 1 in the 2nd for loop.
this is Java rule: in for (int line = 1; line <= width; line++) {..}var line is visible only inside block {}. It is different from C++
0

Can you just add another loop after your first loop like

String r = "";
String space = "";
    for (int i = width; i >= 1; i--)
    {
        r = r + i;
        System.out.println(r);

    }

Try it. not yet tested

Comments

0

You need to use a queue. eg. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html

Enque the numbers till you reach the max, and then start dequing them.

And while you dequeue, you need to apply the reverse

Queue<String> q = new LinkedList<String>();
        for (int i = 1; i <= width; i++)
        {
            r = r + i;
            q.add(r);
            System.out.println(r);

        }

        while(!q.isEmpty()){
            String j = q.remove();
             //reverse j
            System.out.println(reverse(j));
        }

I leave the reversing part for you to do :)

Comments

0
public static void main(String[] args)
{
    int n = 5;

    for(int i=1; i<=n; i++)
    {            
        for (int j=(n*2), k=n; j>1; j--) 
        {
            if (k <= i) 
            {
                System.out.print(k);
            } 
            else 
            {
                System.out.print('*');
            }

            k += (j)-1 > n ? -1 : 1;
        }

        System.out.println();
    }
}

Comments

0

Just tried to implement in scala. Ignore if you don't like it..:-)

 class Triangle extends App
{
  val width = Console.readInt()

  if (width < 2 || width > 9)
  {
     throw new RuntimeException()
  }

  var i, j = 1;

  for (i <- 1 to width)
  {
     for (j <- 1 to i)
     {
        print(j)
     }
     print("\n")
  }

  for (i <- 1 to width)
  {
     for (dummy <- 1 to width-i)
     {
        print(" ")
     }
     for (j <- i to 1 by -1)
     {
       print(j)
     }
     print("\n")
  }
}

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.