2012-09-08 67 views
2

我是一名Java新手。我在C上了一堂課,所以我試圖讓自己擺脫這種思維模式。我正在編寫的程序有一個部分,用戶輸入一個整數,n,然後n之後的字數。這部分然後搜索這些單詞並找到最短的單詞,然後將其返回給用戶。例如,輸入可能是:Java:查找字符串中的最短單詞並將其打印出來

輸入: 4 Java編程的樂趣

OUTPUT: IS

我的代碼目前似乎返回錯誤的單詞。在這種情況下,它返回「PROGRAMMING」,當它返回「IS」時。我想也許你們都可以把我指向正確的方向。

int numwords = scan.nextInt(); 
    String sentence = scan.nextLine(); 
    String shortestword = new String(); 
    String[] words = sentence.split(" "); 
    for (int i = 0; i < numwords; i++){ 
     if (shortestword.length() < words[i].length()){ 
      shortestword = words[i]; 

     } 
    } 
    System.out.printf(shortestword); 

爲了給你什麼,我要怎樣做,我試圖進入的話轉換成字符串,一個想法「一句,」再破該字符串成單個單詞的數組,「字[ ],然後運行一個for循環,通過比較長度和數組中的條目來比較字符串。謝謝您的幫助!

回答

5

你幾乎在那裏,但你的比較檢測最短的單詞是相反的。它應該是:

if (words[i].length() < shortestword.length()) { 

也就是說,如果當前單詞的長度小於以前的最短單詞的長度,將其覆蓋。

另外,不是以空的String開始,而是以第一個字,即words[0]開始。否則,空字符串將總是比陣列中的任何字符串短:

String[] words = sentence.split(" "); 
String shortestword = words[0]; 
for (int i = 1; i < numwords; i++) { // start with 1, because you already have words[0] 
+2

+1。通過點擊鼠標打敗我。 :-) –

+0

謝謝!我感到尷尬的是我的言論被顛倒過來。不幸的是,在我做出這些修改之後,我的程序沒有任何返回,而是終止。 – Batteries

+0

發現單詞[0]實際上需要單詞[1]。感謝您邁出正確的一步! – Batteries

2

您的if語句是錯誤的。這應該工作。

int numwords = scan.nextInt(); 
    String sentence = scan.nextLine(); 
    String shortestword = new String(); 
    String[] words = sentence.split(" "); 
    for (int i = 0; i < numwords; i++){ 
     if (shortestword.length() > words[i].length()){ 
      shortestword = words[i]; 

     } 
    } 
    System.out.printf(shortestword); 
0

這裏有一個版本,使得采用Java 8的Stream API的:

String sentence = "PROGRAMMING IS FUN"; 
List<String> words = Arrays.asList(sentence.split(" ")); 

String shortestWord = words.stream().min(
            Comparator.comparing(
            word -> word.length())) 
            .get(); 

System.out.println(shortestWord); 

你可以通過他們的任何屬性也某種更復雜的對象:如果你有一對夫婦的Person S和你想通過他們的lastName排序,最短的第一,代碼變爲:

Person personWithShortestName = persons.stream().min(
               Comparator.comparing(
               person -> person.lastName.length())) 
               .get(); 
0

的Java 8已使它更簡單。將String陣列轉換爲列表,並使用sorted()按升序比較和排序列表。最後,使用findFirst()獲取列表的第一個值(排序後最短)。

看看,

String[] words = new String[]{"Hello", "name", "is", "Bob"}; 
String shortest = Arrays.asList(words).stream() 
     .sorted((e2, e1) -> e1.length() > e2.length() ? -1 : 1) 
     .findFirst().get(); 

System.out.println(shortest); 
相關問題