簡體   English   中英

我將如何使用 printf() 和輸入單詞的 String 數組在星號框內打印出來

[英]How would I use printf() and a String array of inputed words to print out within a box of asterisks

在這種格式中,'Nivla' 將位於字符串列表中,並且輸入可供用戶格式化。

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

此外,框的大小會隨着字符串數組的行而增加。 例如 ["Nivla is" , "not智能"];

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

另外,我無法像上面一樣將字符串圍繞中心居中。

我目前使用的代碼是:

public void run() {
        Scanner s = new Scanner(System.in);
        ArrayList<String> inputs = new ArrayList<>();
        String input;
        do {
            input = s.nextLine();
            inputs.add(input);
        } while(!input.equals(""));
        printBox(inputs);
    }

    public void printBox(ArrayList inputs) {
        for (int i = 0; i < inputs.size(); i++) {
            System.out.printf("*\t%s\t*\n", inputs.get(i));
        }
    }

有什么辦法可以解決我的問題嗎?

您需要根據最長輸入的長度來確定空格量,而不僅僅是在每一側打印制表符。 您還應該在 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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM