ICSE Computer Science Java Programs | IT Developer
IT Developer

Java Programs - Solved 2009 ICSE Computer Science Paper



Share with a Friend

Solved 2009 ICSE Computer Science Paper

Class 10 - ICSE Computer Science Solved Papers

Longest Word Program - ICSE 2009 Computer Science

Write a program to input a sentence and print the number of characters found in the longest word of the given sentence.
For example, if s = “India is my country” then the output should be 7.

import java.util.Scanner; class Longest{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.print("Enter the sentence: "); String s = in.nextLine(); String l = ""; String w = ""; for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(ch == ' ' || i == s.length() - 1){ if(w.length() > l.length()) l = w; w = ""; } else if(Character.isLetterOrDigit(ch)) w += ch; } int len = l.length(); System.out.println("Longest word length: " + len); } }

Output

 
 OUTPUT : 
Enter the sentence: India is my country.
Longest word length: 7