我将如何使用printf和输入单词的String数组在一个星号框中打印出来

问题描述

采用这种格式,其中“ Nivla”将位于字符串列表中,并且输入可由用户设置格式。

x = torch.randn(3,requires_grad=True)
y = x * 2
J = torch.zeros(x.shape[0],x.shape[0])
for i in range(x.shape[0]):
    v = torch.tensor([1 if j==i else 0 for j in range(x.shape[0])],dtype=torch.float)
    y.backward(v,retain_graph=True)
    J[:,i] = x.grad
    x.grad.zero_()
print(J)

此外,该框的大小将随着字符串数组的行而增加。例如。 [“ Nivla是”,“不聪明”];

************
*   Nivla  *
************

此外,我在像上面那样将字符串围绕中心居中遇到麻烦。

我当前使用的代码是:

**********************
*      Nivla is      *
*   not intelligent  *
**********************

有什么办法可以解决我的问题?

解决方法

您需要根据最长输入的长度来确定空格的数量,而不仅仅是在每侧打印标签。您还应该在printBox方法中添加一个padding参数,以指定要在单词的两边放置多少空格。

这是一种可能效果不错的解决方案:

    int max = 0;
    int padding = 10;
    public void run() {
        Scanner s = new Scanner(System.in);
        ArrayList<String> inputs = new ArrayList<>();
        String input;
        do {
            input = s.nextLine();
            inputs.add(input);
            max = Math.max(max,input.length());
        } while(!input.equals(""));
        printBox(inputs,padding);
    }

    public void printBox(ArrayList inputs,int padding) {
        printStars();
        // go to size - 1 because the last input is always ""
        for (int i = 0; i < inputs.size() - 1; i++) {
            int len = ((String)inputs.get(i)).length();
            int frontPad = (max + len)/2 + padding;
            // need to round or else sometimes the padding will be one too short
            int backPad = padding + (int)Math.round(((max - len)/2.0));
            System.out.printf("*%" + frontPad + "s%" + backPad + "s\n",inputs.get(i),"*");
        }
        printStars();
    }

    private void printStars() {
        for (int i = 0; i <= max + padding*2; i++) {
            System.out.print("*");
        }
        System.out.println();
    }