Find the Longest and Shortest words in a text file using methods [closed]

三世轮回 提交于 2020-05-14 14:35:13

问题


How can I find the longest word in a text file? I am currently using the following method but I keep getting errors and don't know how to go forward after this.

public static String the_Longest(String text)throws IOException {       
    text = text.toLowerCase();
    String longest =" ";
    Scanner s = new Scanner(new File(text));
    ArrayList<String>long_word=new ArrayList<String>();
    while (s.hasNext()){
        long_word.add(s.next());
    }
    s.close();           
}

回答1:


You can use the same loop that you read the file to compare and select the longest string in the length, like this

public static String findLongest(String fileName) throws IOException {
    Scanner scanner = new Scanner(new File(fileName.toLowerCase()));
    String longest = "", next;
    while (scanner.hasNext()) {
        next = scanner.next();
        if (longest.length() < next.length()) {
            longest = next;
        }
    }
    scanner.close();
    return longest;
}



回答2:


It is analogous to finding the largest number from an array/list of numbers and therefore the same algorithm can be applied in this case.

  1. Store the first word from the file into longest.
  2. Read the next words from the file in a loop. In each iteration of the loop, compare the length of longest with the word and replace the value of longest with the word if word.length() > longest.length().
  3. Return longest when the loop terminates.

Code:

public static String the_Longest(String text) throws IOException {
    text = text.toLowerCase();
    String longest = "", word;
    Scanner s = new Scanner(new File(text));
    if (s.hasNext()) {
        longest = s.next();
    }
    while (s.hasNext()) {
        word = s.next();
        if (word.length() > longest.length()) {
            longest = word;
        }
    }
    s.close();

    return longest;
}


来源:https://stackoverflow.com/questions/61718846/find-the-longest-and-shortest-words-in-a-text-file-using-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!