java實現找出一串單詞中最長的單詞和次數最多的單詞

來源:互聯網
上載者:User
import java.io.*;
import java.util.*;

public class MaxLength {                                     //找出長度最長的單詞

     static void max(int a[],String mystr[]){
        String[] sigstr;
        int max=a[0];
        for(int i=0;i<a.length;i++){
            if(a[i]>max)max=a[i];
            
        }
        //System.out.println(max);
        for(int i=0;i<a.length;i++){                        //找出最長單詞的下標及輸出
            if(a[i]==max)System.out.println("長度最長的單詞是:"+mystr[i]);
        
        }
        
    }
    
    static void nums(String mystr[]){              //找出出現次數最多的單詞,並輸出
        int []a=new int[mystr.length];
        for(int i=1;i<mystr.length;i++){
            a[i]=1;
        }
        
    
        for(int i=1;i<mystr.length;i++)
            for(int j=i-1;j>=0;j--){
                if(mystr[i].equals(mystr[j]))a[i]++;
            }
            
        int max=a[0];
        for(int i=0;i<a.length;i++){
            if(a[i]>max)max=a[i];
            
        }
        //System.out.println(max);
        
        for(int i=0;i<a.length;i++){
            if(a[i]==max)System.out.println("出現次數最多的單詞是:"+mystr[i]);
            
        }
    }
    
    public static void main(String[] args)throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String strs=br.readLine();
        String[] mystr=strs.split(" ");                    //輸入一串單詞,用空格隔開,在此把每個單詞存入數組中
        int[] a=new int[mystr.length];
        for(int i=0;i<mystr.length;i++){
            a[i]=0;
            
        }
        
        for(int i=0;i<mystr.length;i++){
            
            a[i]=mystr[i].length();
        }
        
        max(a,mystr);            //找出長度最長的單詞
        nums(mystr);             //找出出現次數最多的單詞,並輸出
    }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.