簡體   English   中英

如何在不使用數組的情況下在java字符串中找到最短的單詞?

[英]How to find shortest word in a java string without using arrays?

我正在嘗試使用與我在教程中遵循的相同格式的代碼。 它將打印最長的單詞以及最長單詞的長度。 導師告訴我,要找到最短的單詞,我必須將 if 語句翻轉為小於 ('<') 而不是大於...但是,在我輸入任何字符串后,當我運行程序時,它返回:

"最短單詞:"",長度:0"

我不知道如何解決這個問題,所以它尋找一個實際的單詞而不是一個空字符..我想在這里遵循相同的邏輯而不使用數組。

Scanner in = new Scanner(System.in);

System.out.println("Please enter a phrase: ");
String phrase = in.nextLine();


String w = "";
String lw = "";       
int l;
char ch;


phrase = phrase + " ";
l = phrase.length();
int i;
for (i=0; i < l; i++) {
    ch = phrase.charAt(i);
    if(ch != ' ') {
        w = w + ch;
    } else {
        if(w.length() > lw.length()) {
            lw = w;
        }
        w = "";
    }
}

System.out.println("Longest Word: \"" + lw + "\", length: "+ lw.length());

你必須做的一件事就是改變

if(w.length() > lw.length())

if(w.length() < lw.length())

然而,這還不夠,因為lw在初始化為空String ,所以條件將始終為falsew.length()永遠不會 < 0)。

因此,您還必須檢查lw是否仍然為空:

if(w.length() < lw.length() || lw.isEmpty ()) {
    lw = w;
}

完整代碼:

Scanner in = new Scanner(System.in);

System.out.println("Please enter a phrase: ");
String phrase = in.nextLine();

String w = "";
String lw = "";       
int l;
char ch;

phrase = phrase + " ";
l = phrase.length();
int i;
for (i=0; i < l; i++) {
    ch = phrase.charAt(i);
    if(ch != ' ') {
        w = w + ch;
    } else {
        if(w.length() < lw.length() || lw.isEmpty ()) {
            lw = w;
        }
        w = "";
    }
}

System.out.println("Shortest Word: \"" + lw + "\", length: "+ lw.length());

暫無
暫無

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

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