S. West
S. West

Reputation: 43

make a string displayed as a box

I just cannot figure out how to get the result I'm looking for. Here's my code

 import java.util.Scanner;
 public class StringInABox
 {
 public static void main(String[]args)
 {
      Scanner scan = new Scanner(System.in);

      System.out.println("Enter a phrase or word!");
      String Phrase = scan.nextLine();
      String CapPhrase = Phrase.toUpperCase();
      int PhraseLength = CapPhrase.length();
      String SidePhrase = CapPhrase.substring(1);
      int SidePhraseL = SidePhrase.length()-1;

      for (int Letter = 0; Letter<PhraseLength; Letter++)
           System.out.print(CapPhrase.charAt(Letter)+" ");
      System.out.println();

      for (int Letter = 0; Letter<SidePhraseL; Letter++)
          System.out.println(SidePhrase.charAt(Letter));

      for (int Letters = SidePhraseL-1; Letters>=0; Letters--)
      { for (int Space=0; Space <= PhraseLength*2-3;Space++)
           System.out.print(" ");
      System.out.println(SidePhrase.charAt(Letters));}


      for (int Letter = PhraseLength-1; Letter>=0; Letter--)
          System.out.print(CapPhrase.charAt(Letter)+" ");
      }
  }         

The result is supposed to be something like:

   H E L P 
   E     L
   L     E
   P L E H

But I can only get:

   H E L P 
   E
   L
         L
         E
   P L E H

I've run out of ideas. I'm a beginner and this shouldn't take advanced coding.

Upvotes: 3

Views: 189

Answers (4)

user3335083
user3335083

Reputation:

here's my answer. i've re-named things according to java naming standards, addressed the memory leak (Scanner wasn't closed), used methods as one does, and addressed the fact that the word phrase implies that there could be words with spaces in between.

public static void main(String[] args) {

    try (Scanner scan = new Scanner(System.in)) {

        System.out.println("Enter a phrase or word!");
        String phrase = scan.nextLine();
        phrase = phrase.toUpperCase();
        phrase = cleanUpWordBoundaries(phrase);

        for (int letter = 0; letter < phrase.length(); letter++) {
            System.out.print(phrase.charAt(letter) + " ");
        }

        System.out.println();

        printSidePhrase(phrase);

        for (int letter = phrase.length() - 1; letter >= 0; letter--) {
            System.out.print(phrase.charAt(letter) + " ");
        }
    }
}

private static void printSidePhrase(String phrase) {

    int startIndex = 1;
    int lastIndex = phrase.length() - 2;

    for (int letter = 1; letter < phrase.length() - 1; letter++) {

        System.out.print(phrase.charAt(startIndex));

        // print spaces
        for (int i = 0; i < (phrase.length() - 2); i++) {
            System.out.print("  ");
        }

        System.out.print(" " + phrase.charAt(lastIndex));
        System.out.println();
        startIndex++;
        lastIndex--;
    }
}


private static String cleanUpWordBoundaries(String phrase) {

    String[] theWords = phrase.split("\\b");
    String newPhrase = new String();
    for (int i = 0; i < theWords.length; i++) {

        newPhrase += theWords[i];
        i++;
    }

    return newPhrase;
}

from running the program:

Enter a phrase or word!
w00 h00 bandit
W 0 0 H 0 0 B A N D I T 
0                     I
0                     D
H                     N
0                     A
0                     B
B                     0
A                     0
N                     H
D                     0
I                     0
T I D N A B 0 0 H 0 0 W 

Upvotes: 0

Mr.Nice
Mr.Nice

Reputation: 1

I'm so lucky to answer your question! Attention! The key of the problem is that The cursor only go to next line,it won't go back previous line. When the second loop end,the result is as follow:

H E L P 
E
L

The print of the thirdly loop begins at line 4, So the print results of next line is as follow:

H E L P 
E
L
      L

I have coded the code as follow:

Scanner s = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String pharase = s.nextLine().toUpperCase();
int length = pharase.length();
char[] strArr = pharase.toCharArray();
for (int row = 0; row <= length-1 ; row++) {
    for (int column = 0; column <= length -1 ; column++) {
        System.out.print(row>0&&row<length-1&&column>0&&column<length-1
        ?" ":strArr[Math.abs(row-column)]);
        System.out.print(" ");
    }
    System.out.println();
}

the result of input "youarehandsome":

Y O U A R E H A N D S O M E 
O                         M 
U                         O 
A                         S 
R                         D 
E                         N 
H                         A 
A                         H 
N                         E 
D                         R 
S                         A 
O                         U 
M                         O 
E M O S D N A H E R A U O Y 

Upvotes: 0

sellc
sellc

Reputation: 378

An incredibly helpful tactic for solving tricky problems is to map/draw/record everything that's changing and search for patterns. So we'll start by doing just that. For simplicity of tracking values I'll show the process in an array.

String keyword = "test"

Result will look something like this.

[t][e][s][t]
[e][ ][ ][s]
[s][ ][ ][e]
[t][s][e][t]

The first row is equal to the string but we'll replace the letters with values corresponding to the index of the character in the string. Space will be equal to 0.

[1][2][3][1]
[2][0][0][3]
[3][0][0][2]
[1][3][2][1]

If we take these values and put them into one line we would end up with

1231200330021321
1231 2003 3002 1321  //Easier to read version

The first and last line are reversed and the second and third line are reversed. Thus, we can produce the output with three index counters. Each index counter is referencing a character within the original string

The first index counter will be for the full string to be read forward and backwards.

[t][e][s][t]    //From 0 -> (keyword.length-1)
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[t][s][e][t]    //From (keyword.length-1) -> 0

The second counter will be used to index up on the left side and the third counter will be used to index down on the right side.

[ ][ ][ ][ ]    //Be aware of possible out of bounds index errors
[e][ ][ ][s]    //From 1 -> (keyword.length-2)
[s][ ][ ][e]    //From (keyword.length-2) -> 1
[ ][ ][ ][ ]

Upvotes: 0

Sudheesh Singanamalla
Sudheesh Singanamalla

Reputation: 2297

You're quite close but the problem here is the order of the for loops. To get the required output as follows:

E          L
L          E

You need to print both of these characters in the same loop i.e. when it's printing on the same line. So you need the IndexFromFront and IndexFromBack variables which store the value of E and L respectively.

After your initial loop to print the characters H E L P

for (int Letter = 0; Letter < PhraseLength; Letter++)
   System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();

You need to start from the first index i.e. 1 to access E and the value of IndexFromBack would be PhraseLength-1-(IndexFromFront). Now that you have the indices of the values that you'd have to print from the original string, you need to get the right spacing i.e. 2*(PhraseLength-1)-1 because you have a space after each character. So your second loop to print the lines

E          L
L          E

should be as follows:

for (int Letter = 1; Letter < PhraseLength-1; Letter++) {
    int IndexFromFront = Letter;
    int IndexFromBack = PhraseLength-1-Letter;
    // Print character from the start of string at given Index 
    System.out.print(CapPhrase.charAt(IndexFromFront));
    // Print required spaces
    for (int Space = 0; Space < 2*(PhraseLength-1)-1; Space++) {
        System.out.print(" ");
    }
    // End space print
    // Print character from the end of string matching the required index
    System.out.print(CapPhrase.charAt(IndexFromBack));
    // Printing on this line is complete, so print a new line.
    System.out.println();
}

and the final line i.e. reverse of given input string can be printed using the loop as follows:

for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
   System.out.print(CapPhrase.charAt(Letter) + " ");
}

Therefore the final code that you'd have is as follows:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);

  System.out.println("Enter a phrase or word!");
  String Phrase = scan.nextLine();
  String CapPhrase = Phrase.toUpperCase();
  int PhraseLength = CapPhrase.length();

  for (int Letter = 0; Letter < PhraseLength; Letter++)
   System.out.print(CapPhrase.charAt(Letter) + " ");
  System.out.println();

  for (int Letter = 1; Letter < PhraseLength - 1; Letter++) {
   int IndexFromFront = Letter;
   int IndexFromBack = PhraseLength - 1 - Letter;
   System.out.print(CapPhrase.charAt(IndexFromFront));
   // Print required spaces
   for (int Space = 0; Space < 2 * (PhraseLength - 1) - 1; Space++) {
    System.out.print(" ");
   }
   // End space print
   System.out.print(CapPhrase.charAt(IndexFromBack));
   System.out.println();
  }

  for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
   System.out.print(CapPhrase.charAt(Letter) + " ");
 }
}

Here's a sample output for HELPINGYOUOUT

Enter a phrase or word!
H E L P I N G Y O U O U T 
E                       U
L                       O
P                       U
I                       O
N                       Y
G                       G
Y                       N
O                       I
U                       P
O                       L
U                       E
T U O U O Y G N I P L E H 

Edit: More readable code

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {

    public static void printSpaces(int phraseLength) {
        for (int space = 0; space < 2 * (phraseLength - 1) - 1; space++) {
            System.out.print(" ");
        }
    }

    public static void printTopRow(String capPhrase, int phraseLength) {
        for (int letter = 0; letter < phraseLength; letter++)
            System.out.print(capPhrase.charAt(letter) + " ");
        System.out.println();
    }

    public static void printIntermediateBoxRows(String capPhrase, int phraseLength) {
        for (int letter = 1; letter < phraseLength - 1; letter++) {
            int indexFromFront = letter;
            int indexFromBack = phraseLength - 1 - letter;
            System.out.print(capPhrase.charAt(indexFromFront));
            // Print required spaces
            printSpaces(phraseLength);
            // End space print
            System.out.print(capPhrase.charAt(indexFromBack));
            System.out.println();
        }
    }

    public static void printLastRow(String capPhrase, int phraseLength) {
        for (int letter = phraseLength - 1; letter >= 0; letter--)
            System.out.print(capPhrase.charAt(letter) + " ");
    }


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

        System.out.println("Enter a phrase or word!");
        String phrase = scan.nextLine();
        String capPhrase = phrase.toUpperCase();
        int phraseLength = capPhrase.length();

        // Print the box
        printTopRow(capPhrase, phraseLength);
        printIntermediateBoxRows(capPhrase, phraseLength);
        printLastRow(capPhrase, phraseLength);
    }
}

Upvotes: 4

Related Questions