将一个字符串显示为一个框

时间:2018-03-19 04:41:53

标签: java string whitespace

我无法弄清楚如何获得我正在寻找的结果。这是我的代码

 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)+" ");
      }
  }         

结果应该是这样的:

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

但我只能得到:

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

我已经没有想法了。我是初学者,不应该采用高级编码。

4 个答案:

答案 0 :(得分:4)

你很接近但这里的问题是for循环的顺序。要获得所需的输出,请按以下步骤操作:

E          L
L          E

您需要在同一个循环中打印这两个字符,即它在同一行上打印时。因此,您需要分别存储IndexFromFrontIndexFromBack值的EL变量。

在您的初始循环后打印字符H E L P

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

您需要从first索引(即1)开始访问EIndexFromBack的值为PhraseLength-1-(IndexFromFront)。现在您已经拥有了必须从原始字符串打印的值的索引,您需要获得正确的间距,即2*(PhraseLength-1)-1,因为每个字符后面都有一个空格。所以你的第二个循环打印线

E          L
L          E

应如下:

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();
}

并且可以使用循环打印最后一行,即给定输入字符串的反向,如下所示:

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

因此,您拥有的最终代码如下:

/* 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) + " ");
 }
}

这是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 

编辑更易读的代码

/* 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);
    }
}

答案 1 :(得分:0)

解决棘手问题的一个非常有用的策略是映射/绘制/记录正在改变和搜索模式的所有内容。所以我们首先要这样做。为了简化跟踪值,我将在数组中显示该过程。

String keyword = "test"

结果将如下所示。

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

第一行等于字符串,但我们将用字符串中字符索引对应的值替换字母。 Space将等于0

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

如果我们采用这些值并将它们放在一行中,我们最终会得到

1231200330021321
1231 2003 3002 1321  //Easier to read version

第一行和最后一行反转,第二行和第三行反转。因此,我们可以使用三个索引计数器生成输出。每个索引计数器都引用原始字符串中的字符

第一个索引计数器将用于向前和向后读取完整字符串。

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

第二个计数器将用于在左侧进行索引,第三个计数器将用于在右侧进行索引。

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

答案 2 :(得分:0)

这是我的答案。我根据java命名标准重新命名了一些内容,解决了内存泄漏问题(扫描程序未关闭),一如既往地使用了方法,并解决了单词短语暗示可能存在空格的单词这一事实。

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;
}

运行程序:

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 

答案 3 :(得分:0)

我很幸运能回答你的问题!注意!问题的关键是光标只到下一行,它不会返回前一行。 当第二个循环结束时,结果如下:

class UserInfoViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let dateToday = Date()
        let calendar = Calendar.current
        let dateToCompare = UserDefaults.standard.object(forKey: "userDefaultDate") as? Date ?? Date.distantPast
        if calendar.isDateInToday(dateToCompare) {
            resetLabel.isHidden = true
        } else {
            UserDefaults.standard.set(dateToday, forKey: "userDefaultDate")
            resetLabel.isHidden = false
        }
    }
}

第三个循环的打印从第4行开始,所以下一行的打印结果如下:

H E L P 
E
L

我已将代码编码如下:

H E L P 
E
L
      L

输入“youarehandsome”的结果:

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();
}