java 使用System.out.println()创建边框

aij0ehis  于 2023-02-02  发布在  Java
关注(0)|答案(7)|浏览(169)

有没有办法创建这样的排列,而String变量sh3不影响边界?我真的被难住了,我的Java知识几乎局限于您在这里看到的内容,如果有帮助的话?

System.out.println("###################################################"); 
System.out.println("#    **** WEST END THEATRE BOOKING SYSTEM ****    #"); 
System.out.println("#                                                 #"); 
System.out.println("#                 T I C K E T                     #"); 
System.out.println("#                                                 #"); 
System.out.println("#     Show:    "+sh3+"                            #"); 
System.out.println("#     Theatre: Her Majesty's                      #"); 
System.out.println("#     Price:   65                                 #"); 
System.out.println("###################################################");
wribegjk

wribegjk1#

既然你知道直线的长度,而且所有的直线都有相同的长度,你可以这样做:
假设n是这一行的长度,由于sh3将从第15位开始,您可以计算sh3之后需要多少个空格。

System.out.println("#     Show:    "+sh3+calcSpaces()+"#");

其中calcSpaces可以很容易地实现,因为您知道sh3的长度。

private String calcSpaces(String sh3) {
    String res = "";
    for(int i = 0; i < n - sh3.length(); i++){
       res += " ";  //You might want to use StringBuilder instead.. 
    }               //it's a good practice, although performance is not 
}                   //significant here

我还建议您阅读有关Formatter的内容。

zsohkypk

zsohkypk2#

我知道我没有为此提供代码,但我指出了思考的过程,然后将实现留给您。
有4个属性在发挥作用,其中你知道total size of line,你也知道length of the string,你知道有多少空间是可以很容易地找到。
您所需要的只是一个循环,它将计算应该留下多少空格。

xesrikrc

xesrikrc3#

就我个人而言,我会使用FormatterPrintStreamprintf()方法。
可以像这样使用printf()

System.out.printf("#     Show:    %-35#\n", sh3);

当第一个字符串被打印出来的时候,其中的%-35sh3加上一些空格所代替,%开始转义序列,-使sh3位于所分配空间的左边,35sh3分配了35个字符的空间,这35个字符中没有被sh3填充的任何一个都用空格填充。
要阅读更多关于printf()语法的信息,请访问此处。
编辑:我忘了提到\n。在String中,\n是一个转义序列,用于创建新行。例如:

System.out.println("abc\n123");

等于

System.out.println("abc");
System.out.println("123");

printf()println()不同,它不会在打印的String末尾创建新行。\n手动创建一个新行,这是使程序按预期运行所必需的。

avwztpqn

avwztpqn4#

是的,这是狡猾的方式:

String sh3 = "StackOverflow";
        String sh4 = "";
        for(int i=0;i<35-sh3.length();i++){
            sh4 += " ";
        }
        sh4 += "#";
        System.out.println("###################################################"); 
        System.out.println("#    **** WEST END THEATRE BOOKING SYSTEM ****    #"); 
        System.out.println("#                                                 #"); 
        System.out.println("#                 T I C K E T                     #"); 
        System.out.println("#                                                 #"); 
        System.out.println("#     Show:    " + sh3 + sh4 ); 
        System.out.println("#     Theatre: Her Majesty's                      #"); 
        System.out.println("#     Price:   65                                 #"); 
        System.out.println("###################################################");
vtwuwzda

vtwuwzda5#

最快的方法是:

System.out.print("#     Show:    " + sh3);
for (int i = 0; i < 34-sh3.length(); i++) {
    System.out.print(" ");
}
System.out.println(" #");
kyvafyod

kyvafyod6#

你可以使用sh3.length()得到sh3的长度,然后你可以添加空格来适应你的边框。

int spacesNum = 35 - sh3.length();
String spaces = "";
for(int i = spacesNum; i > 0; i++){
    spaces += " ";
}

System.out.println("###################################################"); 
System.out.println("#    **** WEST END THEATRE BOOKING SYSTEM ****    #"); 
System.out.println("#                                                 #"); 
System.out.println("#                 T I C K E T                     #"); 
System.out.println("#                                                 #"); 
System.out.println("#     Show:    "+sh3+spaces+"#"); 
System.out.println("#     Theatre: Her Majesty's                      #"); 
System.out.println("#     Price:   65                                 #"); 
System.out.println("###################################################");
wrrgggsh

wrrgggsh7#

这是我两秒钟的贡献。。有点矫枉过正,但它符合要求。。
签入:https://github.com/codegtd/tdd-log-panel

public class ConsolePanel {

  public static void main(String[] args) {

    panel(
         21,
         2,
         3,
         3,
         Border.BOLD,
         Border.DOUBLE,
         Border.DOUBLE,
         Border.THIN,
         true,
         true,
         "My Title", "My First Topic text", "My Second Topic text"
    );
  }

  public static void simplePanel(String... texts) {

    panel(
         21,
         5,
         1,
         1,
         Border.DOUBLE,
         Border.DOUBLE,
         Border.THIN,
         Border.THIN,
         true,
         true,
         texts
    );
  }

  public static void simplePanelScalable(int scale, String... texts) {

    panel(
         scale,
         5,
         1,
         1,
         Border.DOUBLE,
         Border.DOUBLE,
         Border.THIN,
         Border.THIN,
         true,
         true,
         texts
    );
  }

  public static void panel(
       int scale,
       int margin,
       int upSpace,
       int downSpace,
       Border cornersFormat,
       Border centerMarksFormat,
       Border horizontalLinesFormat,
       Border verticalLinesFormat,
       boolean uppercaseTitle,
       boolean centralizeTitle,
       String... titleAndOthers) {

    var estimatedAdjustmentFactor = 3;
    var title = titleAndOthers[0];
    var marginTitle = scale - (title.length() / 2) - estimatedAdjustmentFactor;
    var formattedTexts =
         Stream.of(titleAndOthers)
               .map(item -> item.equals(title) && centralizeTitle ? " ".repeat(
                    marginTitle) + title : item)
               .map(item -> item.equals(
                    title) && uppercaseTitle ? item.toUpperCase() : item)
               .toArray();

    var marginLimitedBySize = Math.min(margin, scale);

    // scale + margin discrepacies eliminated
    if (marginLimitedBySize % 2 != 0) -- marginLimitedBySize;
    if (scale % 2 != 0) ++ scale;

    int fullSize = (scale * 2) - marginLimitedBySize;
    if (fullSize % 2 == 0) ++ fullSize;
    else -- fullSize;

    var whitespaceMargin = " ".repeat(marginLimitedBySize);
    var externalUpSpaces = "\n".repeat(upSpace);
    var externalBottomSpaces = "\n".repeat(downSpace);

    var upperFace = upperLine(scale, cornersFormat, centerMarksFormat, horizontalLinesFormat);
    var divider = middleLine(scale, cornersFormat, centerMarksFormat, horizontalLinesFormat);
    var bottomFace = bottomLine(scale, cornersFormat, centerMarksFormat, horizontalLinesFormat);
    var faceLine = faceLine(verticalLinesFormat);

    var titleTextArea = String.valueOf(fullSize);
    var textPreparation = new StringBuilder();
    textPreparation.append(externalUpSpaces)
                   .append(upperFace)
                   .append(faceLine)
                   .append("%s%%-%ss".formatted(whitespaceMargin, titleTextArea))
                   .append(faceLine)
                   .append("\n")
                   .append(divider);

    // "-1" Because the first element in the Array was used as title
    // The discont-number in bodyTextArea/fullsize, subtract the size of "ordinal-ASC" and ") "
    var bodyTextArea = String.valueOf(fullSize - 4);
    var topicEnumeration = 0;
    var ordinalSymbolEnumerator = '\u2070';
    for (int i = formattedTexts.length - 1; i > 0; i--) {
      ++ topicEnumeration;
      textPreparation.append(faceLine)
                     .append("%s%s%s) %%-%ss".formatted(
                          whitespaceMargin,
                          topicEnumeration,
                          ordinalSymbolEnumerator,
                          bodyTextArea
                     ))
                     .append(faceLine)
                     .append("\n");
    }
    textPreparation.append(bottomFace)
                   .append(externalBottomSpaces);
    System.out.printf(textPreparation.toString(), formattedTexts);
  }

  private static String generateLine(char baseChar, int scale, char BASE_LINE) {

    return
         String
              .valueOf(baseChar)
              .repeat(scale)
              .replace(baseChar, BASE_LINE);
  }

  private static String upperLine(
       int scale,
       Border corner,
       Border centerMark,
       Border line) {

    ArrayList<Character> borderStylingItems = new ArrayList<>();
    switch (corner) {
      case BOLD -> {
        borderStylingItems.add(BoldFont.UPPER_LEFT_CORNER.code);
        borderStylingItems.add(BoldFont.UPPER_RIGHT_CORNER.code);
      }
      case THIN -> {
        borderStylingItems.add(ThinFont.UPPER_LEFT_CORNER.code);
        borderStylingItems.add(ThinFont.UPPER_RIGHT_CORNER.code);
      }
      case DOUBLE -> {
        borderStylingItems.add(DoubleFont.UPPER_LEFT_CORNER.code);
        borderStylingItems.add(DoubleFont.UPPER_RIGHT_CORNER.code);
      }
    }

    switch (centerMark) {
      case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
      case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
      case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
    }

    switch (line) {
      case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
      case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
      case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
    }

    var baseline = generateLine('_', scale, borderStylingItems.get(3));

    return borderStylingItems.get(0) + baseline +
           borderStylingItems.get(2) + baseline +
           borderStylingItems.get(1) + "\n";
  }

  private static String middleLine(
       int scale,
       Border corner,
       Border centerMark,
       Border baseLine
  ) {

    ArrayList<Character> borderStylingItems = new ArrayList<>();
    switch (corner) {
      case BOLD -> {
        borderStylingItems.add(BoldFont.MIDDLE_LEFT.code);
        borderStylingItems.add(BoldFont.MIDDLE_RIGHT.code);
      }
      case THIN -> {
        borderStylingItems.add(ThinFont.MIDDLE_LEFT.code);
        borderStylingItems.add(ThinFont.MIDDLE_RIGHT.code);
      }
      case DOUBLE -> {
        borderStylingItems.add(DoubleFont.MIDDLE_LEFT.code);
        borderStylingItems.add(DoubleFont.MIDDLE_RIGHT.code);
      }
    }

    switch (centerMark) {
      case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
      case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
      case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
    }

    switch (baseLine) {
      case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
      case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
      case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
    }

    var divider = generateLine('_', scale, borderStylingItems.get(3));

    return borderStylingItems.get(0) + divider +
           borderStylingItems.get(2) + divider +
           borderStylingItems.get(1) + "\n";
  }

  private static String bottomLine(
       int scale,
       Border corner,
       Border centerMark,
       Border baseLine) {

    ArrayList<Character> borderStylingItems = new ArrayList<>();
    switch (corner) {
      case BOLD -> {
        borderStylingItems.add(BoldFont.LOWER_LEFT_CORNER.code);
        borderStylingItems.add(BoldFont.LOWER_RIGHT_CORNER.code);
      }
      case THIN -> {
        borderStylingItems.add(ThinFont.LOWER_LEFT_CORNER.code);
        borderStylingItems.add(ThinFont.LOWER_RIGHT_CORNER.code);
      }
      case DOUBLE -> {
        borderStylingItems.add(DoubleFont.LOWER_LEFT_CORNER.code);
        borderStylingItems.add(DoubleFont.LOWER_RIGHT_CORNER.code);
      }
    }

    switch (centerMark) {
      case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
      case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
      case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
    }

    switch (baseLine) {
      case BOLD -> borderStylingItems.add(BoldFont.BASE_LINE.code);
      case THIN -> borderStylingItems.add(ThinFont.BASE_LINE.code);
      case DOUBLE -> borderStylingItems.add(DoubleFont.BASE_LINE.code);
    }

    var baseline = generateLine('_', scale, borderStylingItems.get(3));

    return borderStylingItems.get(0) + baseline +
           borderStylingItems.get(2) + baseline +
           borderStylingItems.get(1) + "\n";
  }

  private static Character faceLine(Border corner) {

    return switch (corner) {
      case BOLD -> BoldFont.FACE_LINE.code;
      case THIN -> ThinFont.FACE_LINE.code;
      case DOUBLE -> DoubleFont.FACE_LINE.code;
    };
  }

  private enum BoldFont {

    FACE_LINE('\u2503'),
    BASE_LINE('\u2501'),
    UPPER_LEFT_CORNER('\u250F'),
    UPPER_RIGHT_CORNER('\u2513'),
    MIDDLE_LEFT('\u2523'),
    MIDDLE_RIGHT('\u252B'),
    LOWER_LEFT_CORNER('\u2517'),
    LOWER_RIGHT_CORNER('\u251B');

    private final char code;

    BoldFont(char code) {

      this.code = code;
    }
  }

  private enum ThinFont {

    FACE_LINE('\u2502'),
    BASE_LINE('\u2500'),
    UPPER_LEFT_CORNER('\u250C'),
    UPPER_RIGHT_CORNER('\u2510'),
    MIDDLE_LEFT('\u252C'),
    MIDDLE_RIGHT('\u2524'),
    LOWER_LEFT_CORNER('\u2514'),
    LOWER_RIGHT_CORNER('\u2518');

    private final char code;

    ThinFont(char code) {

      this.code = code;
    }
  }

  private enum DoubleFont {

    FACE_LINE('\u2551'),
    BASE_LINE('\u2550'),
    UPPER_LEFT_CORNER('\u2554'),
    UPPER_RIGHT_CORNER('\u2557'),
    MIDDLE_LEFT('\u2560'),
    MIDDLE_RIGHT('\u2563'),
    LOWER_LEFT_CORNER('\u255A'),
    LOWER_RIGHT_CORNER('\u255D');

    private final char code;

    DoubleFont(char code) {

      this.code = code;
    }
  }

  private enum Border {
    BOLD, THIN, DOUBLE
  }
}

相关问题