Java: Find the longest word in a text file
Write a Java program to find the longest word in a text file.
Sample Solution:
Java Code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Exercise18 {
public static void main(String [ ] args) throws FileNotFoundException {
new Exercise18().findLongestWords();
}
public String findLongestWords() throws FileNotFoundException {
String longest_word = "";
String current;
Scanner sc = new Scanner(new File("/home/students/test.txt"));
while (sc.hasNext()) {
current = sc.next();
if (current.length() > longest_word.length()) {
longest_word = current;
}
}
System.out.println("\n"+longest_word+"\n");
return longest_word;
}
}
Sample Output:
general-purpose,
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to read first 3 lines from a file.
Next: Java Collection Exercises
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics