This is a Java program that reads words from a file and finds the longest word in it. Here's how it works:
Note that the program assumes that the file file.txt exists in the same directory as the program. If the file is located elsewhere, you need to specify the full path to it. Also, the program doesn't handle cases where there are ties for the longest word; it simply returns the first longest word it finds.
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class Longest_Word { public static void main(String[] args) throws FileNotFoundException { new Longest_Word().find_LongestWords(); } public String find_LongestWords() throws FileNotFoundException { String long_word = ""; String cur; Scanner input = new Scanner(new File("file.txt")); while (input.hasNext()) { cur = input.next(); if (cur.length() > long_word.length()) { long_word = cur; } } System.out.println(long_word); return long_word; } }
Programs
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions