Search code examples
javanested-loops

Is there a way to print out text without 'adding' spaces?


I am working on a method that outputs this:

**********
*        *
*        *
*  Hello *
*        *
*        *
**********

I have a feeling I need to use .substring method but have gotten stuck. A lot of sources have told me to use nested loops and that is what I have done except when I go and try to place my message into the shape an extra space is added naturally caused by the string shifting the star char to the right:

***********
*         *
*         *
*  Hello    *
*         *
*         *
***********

I'm using java 8. int n is the amount of c characters are placed on the top and bottom of the shape. String message would be hello in this case.

public void boxThing(int n, char c, String message) {
        for(int i = 0; i <= (n/2); i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || i == n) {
                    System.out.print(c);
                }
                else if(j == 0 || j == n) {
                    System.out.print(c);
                }
                else if(j==n/2 && i==((n/2)/2)+1){
                    System.out.print(message);
                }
                else{
                    System.out.printf(" ");
                }
            }
            System.out.println();
        }
        for(int i =0; i<=n; i++){
            System.out.print(c);
        }
    }

Solution

  • You have to add the length of the message to j and minus by 1, for example, the word "hello" takes 5 positions. Since j will add 1 on the loop for the word you just have to set j to be the j + message length -1 when it reaches the second else if condition. Refer below.

    for(int i = 0; i <= (n/2); i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || i == n) {
                System.out.print(c);
            }
            else if (j == 0 || j == n) {
                System.out.print(c);
            }
            else if (j == n/2 && i == ((n/2)/2)+1) {
                System.out.print(message);
                j = j + message.length() - 1;
            }
            else {
               System.out.print(" ");
            }
        }
        System.out.println();
    }
    for(int i = 0; i <= n; i++){
        System.out.print(c);
    }