gpt4 book ai didi

Java,在控制台中精确地间隔文本中的单词

转载 作者:行者123 更新时间:2023-12-01 18:46:00 25 4
gpt4 key购买 nike

以下说明来自问题 4:“Justifying Text”,来自 Programming Olympiad 2012: Round 1 :

Write a program that will take the provided text and print it out in a column of a specified width (just like in a newspaper). Words at the end of a line that would end beyond the length specified, must be moved to the next line. Spaces must be added between the words so that each line is exactly the specified width and the spaces are as evenly distributed over the line as possible. If only one word fits in a line, that word must be left-aligned. The width of a column will always be greater than or equal to nine. Use the following text: “A great discovery solves a great problem but there is a grain of discovery in the solution of any problem”

我使用的方法是将要使用的位数设置为宽度集,例如。宽度 20 = 20 位数字。每个数字都可以用文本中的字母或空格填充。这种方法效果不是很好,因为有些字母的长度比其他字母的长度要宽。

你认为我的方法可以吗?如何使用不同的算法产生更好的结果?我该如何改进下面的代码?

这是我的解决方案:

public class main {

public static void main(String[] args) {
String text = "A great discovery solves a great problem but there is a grain of discovery in the solution of any problem";
int input = Integer.valueOf(JOptionPane.showInputDialog("Input: "));

String[] words = text.split(" ");
int amDigits = 0;
ArrayList<String> wordsOfLine = new ArrayList<String>();
String line = "";

for(int i = 0; i < words.length; i++) {
if(amDigits < input) {
amDigits += words[i].length() + 1;
wordsOfLine.add(words[i]);

}
else {
// System.out.println("Words: " + wordsOfLine);

int totalWhiteSpace = 0;
for(int a = 0; a < wordsOfLine.size(); a++) {
totalWhiteSpace = input - wordsOfLine.get(a).length();

}
int singleWhiteSpace = Math.round((float) totalWhiteSpace/(float) wordsOfLine.size() - 1);
System.out.println(singleWhiteSpace);

for(int b = 0; b < wordsOfLine.size(); b++) {
line += wordsOfLine.get(b);
for(int c = 0; c < singleWhiteSpace; c++) {
line += " ";

}

}

System.out.println(line);

amDigits = 0;
line = "";
wordsOfLine = new ArrayList<String>();
i--;
}
}
}
}

最佳答案

  1. 所有代码都塞在 public static void main 中。创建至少两个具有直观名称的方法,以解释它们的作用以使其更具可读性。这样我就可以浏览一下并了解您正在做的事情的主题。

  2. for 循环在循环的每次迭代中检查数组的大小。每次迭代都重新扫描数组会浪费处理器时间。

  3. 不要将类称为“main”,而是为其指定一个名称来说明其功能。例如“SetFormattedSpacingWidth”或捕捉其本质的东西。

  4. 有一个三重嵌套的 for 循环。三重嵌套的 for 循环通常可以以多态方式重写,以仅具有一个或最多两个 for 循环。

  5. 您正在使用旧的 for 循环方式,而不是这样:

    for(int b = 0; b < wordsOfLine.size(); b++) {
    line += wordsOfLine.get(b);
    //access words via: wordsOfLine.get(b);
    }

    使用新的java foreach loop减去一行并使其更具可读性。

    for(String words : wordsOfLine) {
    //access words via: 'words'
    }
  6. 在递增 i 的 for 循环内递减 i--?这确实令人困惑。

  7. 可能会发生被零除异常。你甚至不需要捕获那些。它们应该是不可能发生的。

这是我对这个有趣问题的尝试:

import java.io.IOException;
import java.util.ArrayList;

public class DoFormattedColumnWidth {

public static void main(String[] args) {

String msg = "Contrary to popular belief, Lorem Ipsum is not simply " +
"random text. It has roots in a piece of classical Latin " +
"literature from 45 BC, making it over 2000 years old. Richard " +
"McClintock, a Latin professor at Hampden-Sydney College in " +
"Virginia, looked up one of the more obscure Latin words, " +
"consectetur, from a Lorem Ipsum passage, and going through the " +
"cites of the word in classical literature, discovered the " +
"undoubtable source. Lorem Ipsum comes from sections 1.10.32 and " +
"1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good " +
"and Evil) by Cicero, written in 45 BC. This book is a treatise on " +
"the theory of ethics, very popular during the Renaissance. The first " +
"line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a " +
"line in section 1.10.32.";
ArrayList<String> lines =
justifyText(msg, 25);

for(String line : lines){
System.out.println(line);
}
}
public static ArrayList<String> justifyText(String text, int width){

ArrayList<String> lines = new ArrayList<String>();

String[] words = text.split(" ");

String currentLine = "";
int currentWord = 0;
int len = words.length;
int numberOfWordsThisLine=0;
while (currentWord < len){
if ((currentLine.length() + words[currentWord].length()) <= width ||
(currentLine.length() + words[currentWord].length()) > width &&
numberOfWordsThisLine == 0){

currentLine = currentLine + " " + words[currentWord];
currentWord++;
numberOfWordsThisLine++;
if (currentWord == len)
lines.add(currentLine.trim());
}
else{
currentLine = infuseLineWithSpaces(currentLine.trim(),
width - (currentLine.trim().length()));
lines.add(currentLine.trim());
currentLine = "";
numberOfWordsThisLine=0;
}
}
return lines;
}
public static String infuseLineWithSpaces(String text, int numSpaces){

String newText = "";
if (numSpaces == 0) return text;
else if (numSpaces == 1) return text + " ";
else if (numSpaces > 1){
String[] words = text.split(" ");
int numberOfWords = words.length;

int left = (numSpaces + (numberOfWords-1));
int right = ((words.length-1));

int numberSpacesToAddEachWord = (int)((double)left / (double)right);

for(int x = 0; x < numberOfWords; x++){
if (x == numberOfWords)
newText = newText + words[x];
else
newText = newText + words[x] + getSpaces(numberSpacesToAddEachWord);
}
}
else
return text;
return newText;
}
public static String getSpaces(int spaces){
String text = "";
for(int x = 0; x < spaces; x++){
text+= " ";
}
return text;
}
}

哪些输出:

Contrary    to    popular
belief, Lorem Ipsum is
not simply random text.
It has roots in a piece
of classical Latin
literature from 45 BC,
making it over 2000 years
old. Richard McClintock,
a Latin professor at
Hampden-Sydney College in
Virginia, looked up one
of the more obscure Latin
words, consectetur, from
a Lorem Ipsum passage,
and going through the
cites of the word in
classical literature,
discovered the
undoubtable source. Lorem
Ipsum comes from sections
1.10.32 and 1.10.33 of
"de Finibus Bonorum et
Malorum" (The Extremes of
Good and Evil) by Cicero,
written in 45 BC. This
book is a treatise on the
theory of ethics, very
popular during the
Renaissance. The first
line of Lorem Ipsum,
"Lorem ipsum dolor sit
amet..", comes from a
line in section 1.10.32.

它并不完美,因为单词之间的间距是由行中的单词数除以填充间隙所需的额外空格数来确定的,因此右行并不完全合理。但它比以前更有道理。

关于Java,在控制台中精确地间隔文本中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17793512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com