Java: Find the longest word in a text file
Java Input-Output: Exercise-18 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/io/java-io-exercise-18.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics