3 回答

TA贡献1860条经验 获得超8个赞
在您的 while 块中(在 {} 对之后while
的行)中,您有某人输入的行。它是字符串类型。
如果你在 Java 中查找 String 类,你会发现它有一个 for 的方法length()
,所以这就是你获取行长的方法(line.length()
返回一个 int 长度)。
要跟踪最长的行,您需要在 where count
is declared 的地方声明一个变量,该变量将存储输入的最长行。对于每条线,将您拥有的线的长度与迄今为止遇到的最长长度进行比较;如果当前是最长的,则存储它的长度(和它的值,如果你也需要的话,在一个声明在 count 和最长行值旁边的变量中)。我指出将它们放在哪里的原因是它们需要在 while 循环之外声明,以便您可以在循环完成后引用它们。
Shortest 以相同的方式完成,但变量不同。
祝你好运 - 如果需要,请发布更多问题!我试图给你足够的信息,让你可以自己编写实际的代码,但很难衡量那是多少。

TA贡献1966条经验 获得超4个赞
它会是这样的:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
int count = 0;
String shortest = String.format("%0" + 10000 + "d", 0).replace("0", "x");
String longest = "";
while (!(line = input.nextLine()).isEmpty()) {
System.out.println("Enter word: ");
count += line.length();
if (line.length() > longest.length())
longest = line;
if(line.length() < shortest.length())
shortest = line;
}
System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " + longest + " with length " + longest.length());
System.out.println("The shortest word was: " + shortest + " with length " + shortest.length());
}
}

TA贡献1779条经验 获得超6个赞
根据遇到的第一个单词设置最小和最大的单词大小。然后继续比较值以确定大小。如果单词大小相同,这也可以处理大小写。
public static void main(String[] args) {
String line;
Scanner input = new Scanner(System.in);
int count = 0;
int largestSize = 0;
int smallestSize = 0;
String longestWord = "";
String shortestWord = "";
while (!(line = input.nextLine()).isEmpty()) {
System.out.println("Enter word: ");
count++;
//Initialize sizes and words on first round.
if (count == 1) {
smallestSize = largestSize;
shortestWord = line;
}
//Do the comparisons.
if (largestSize <= line.length()) {
largestSize = line.length();
longestWord = line;
} else if (smallestSize > line.length()) {
smallestSize = line.length();
shortestWord = line;
}
}
System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " + longestWord + " with length " + longestWord.length());
System.out.println("The shortest word was: " + shortestWord + " with length " + shortestWord.length());
}
添加回答
举报