簡體   English   中英

如何在 Java 中實現 justify() 方法

[英]How to implement justify()-method in Java

我正在嘗試制作自己的justify() -方法,該方法將字符串和 integer 作為輸入,並填充間距,以便字符串與給定的 integer 具有相同的長度。 我已經按照這個問題的答案去做了。

我希望我的代碼能夠像這樣工作:

Input = "hi hi hi" 20
Output = hi       hi       hi

我的代碼如下所示:

//Add spaces to string until it is of desired length
static String justify(StringBuilder text, int width) {

    String[] inputLS = text.toString().split(" ");                //Split string into list of words

    //Sum the length of the words
    int sumOfWordLengths = 0;
    for (String word : inputLS){ sumOfWordLengths += word.length(); }

    int padding = width-sumOfWordLengths;                         //How much spacing we need
    String lastWord = inputLS[inputLS.length - 1];                //Last word in list of strings

    //Remove the last word
    ArrayList<String> withoutLast = new ArrayList<>
                                (Arrays.asList(inputLS).subList(0, inputLS.length - 1));

    StringBuilder result = new StringBuilder();                   //Initialize StringBuilder

    //Iterate over strings and add spacing (we do not add spacing to the last word)
    while (padding > 0){
        for(String word : withoutLast){
            result.append(word).append(" ");
            padding--;
        }
    }
    result.append(lastWord);                                      //Add the last word again
    return result.toString();
}


public static void main(String[] args) {
        // IO
        Scanner scanner = new Scanner(System.in);                       //Initialize scanner
        System.out.println("Please enter a string and an integer: ");   //Ask for input from user

        String line = scanner.nextLine();          //Get input-string from user
        String[] strings = line.split(" ");        //Split string at " " into list of strings
        String text = strings[0];                  //Get first element from list as string
        int width = Integer.parseInt(strings[1]);  //Get second element from list as an int

        // Create a string with three times the input text with spaces between
        StringBuilder forJustify = new StringBuilder();
        for(int i=0; i<3; i++){ forJustify.append(text).append(" "); }

        // Make sure the length of the string is less than the given int
        if (text == null || text.length() > width) {
            System.out.println(text);
            throw new IllegalArgumentException("Whoops! Invalid input. Try again.");
        }

        System.out.println("Gave this as input:\t" + forJustify);
        System.out.println("Justify:\t\t\t" + justify(forJustify, width));
    }

這給了我這個 output:

Please enter a string and an integer: 
hi 20
Gave this as input: hi hi hi 
Justify:            hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi

但我想要這個 output:

Please enter a string and an integer: 
hi 20
Gave this as input: hi hi hi 
Justify:            hi       hi       hi

我知道while-loop有問題,但我不明白如何解決它。 感謝所有幫助!

這個解決方案使用printf()非常簡單

String test = "hi hi hi";
String[] tokens = test.split(" ");
int spacing = 20;
for (String token : tokens) {
    System.out.printf("%" + spacing + "s", token);          
}
System.out.println();

output(右對齊):

                  hi                  hi                  hi

對於左對齊解決方案,只需在百分號后添加-

for (String token : tokens) {
    System.out.printf("%-" + spacing + "s", token);         
}
System.out.println();

輸出:

hi                  hi                  hi                  

更新:將理由提取為 function:

public static void justify(int spacing, boolean leftJustified, String...words) {
    for (String word : words) {
        System.out.printf("%" + (leftJustified ? "-" : "") + spacing + "s", word);                      
    }
    System.out.println();
}

要使用,

public static void main(String[] args) {
    String test = "hi hi hi";
    String[] tokens = test.split(" ");
    int spacing = 20;
        
    justify(spacing, false, tokens); // right-justified
    justify(spacing, true, tokens); // left-justified
}

在使用上面的答案后,我想出了這個解決方案:

static String justify(StringBuilder text, int width) {

        //Turn StringBuilder into an arraylist of strings
        String[] words = text.toString().split(" ");
        List<String> arraylist = Arrays.asList(words);

        //Find the length of the words and length of the padding needed
        int lengthOfWords = 3 * arraylist.get(0).length();
        int pad = width - lengthOfWords;

        //Add padding by using format on each word separately and then combine the strings and add last word
        String result;
        if (pad % 2 == 0){
            String temp1 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            String temp2 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            result = temp1 + temp2 + words[0];
        } else {
            pad--;
            String temp1 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            String temp2 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            result = temp1 + temp2 + words[0];

            //Turn string into arraylist
            ArrayList<Character> cs = new ArrayList<>();
            for (char c : result.toCharArray()){ cs.add(c); }

            //Add last whitespace between first and second word
            int index = nextSpaceIndex(cs);
            cs.add(index, ' ');

            //Turn arraylist back to string
            StringBuilder str = new StringBuilder();
            for (Character c : cs) { str.append(c); }
            result = str.toString();
        }
        return result;
    }

這給了我這個 output:

Please enter a string and an integer: 
hi 20
Justified:      |hi       hi       hi|

暫無
暫無

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

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