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());
}
添加回答
舉報