Java中心对齐字符串

时间:2019-06-08 19:54:03

标签: java alignment center

我正在尝试使用jlist,希望在不使用任何额外资源的情况下做到这一点。有什么办法吗?

包装测试;

import java.util.Arrays; 公共类Main {

public static void main(String[] args) {

    String s1 = " ";
    int n = 50;
    char[] equal = new char[n];
    Arrays.fill(equal, '=');
    System.out.println(new String(equal));

    //int z = 12;
    //char[] spaces = new char[z];
    //Arrays.fill(spaces,' ');
    //System.out.println(new String(spaces));

    //String h = "START BATTLESHIP";
    //System.out.println(String.format("%-60s",h));
    //System.out.println(new String(spaces));
    System.out.println(getPaddedString("START BATTLESHIP"+s1));
    System.out.println(new String(equal));
}

private static String getPaddedString(String start_battleship) {
    return start_battleship;
}

}

公共级战列舰{

private static String equal;
//private String spaces;

public battleship(String equal, String spaces) {
    this.equal = equal;
    //    this.spaces = spaces;
}

public static String getPaddedString(String str, char paddingChar) {
    int maxPadding = 100;
    int length = str.length();
    int padding = (maxPadding - length) / 2;
    String empty = "", space = " ";
    int extra = (length % 2 == 0) ? 1 : 0;
    String leftPadding = "%" + padding + "s";
    String rightPadding = "%" + (padding - extra) + "s";
    String strFormat = leftPadding + "%s" + rightPadding;
    String formattedString = String.format(strFormat,empty, space, empty);
    String paddedString = formattedString;//.replace(' ', paddingChar).replace(equal, str);
    return paddedString;

我希望战舰在中间对齐

0 个答案:

没有答案