write a program by using scanner class to input a sectence. Display the longest word along with the number if characters in it.
Answers
Answered by
2
Heya friend!!
Here's your answer....
import java.util.Scanner;
class Longest
{
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
String str, cword = "", maxword = "";
int len, maxlen = 0, clen = 0, i;
char ch;
System.out.print("Enter the sentence: ");
str = sc.nextLine();
str = ' ' + str;
len = str.length();
for (i = 0; i < len; i++)
{
ch = str.charAt(i);
if (ch != ' ')
{
cword = cword + ch;
}
else
{
clen = cword.length();
if (clen > maxlen)
{
maxlen = clen;
maxword = cword;
}
cword = "";
}
}
System.out.println("The longest word is: " + maxword);
System.out.println("The number of characters in it: " + maxlen);
}
}
Thanks!!
Here's your answer....
import java.util.Scanner;
class Longest
{
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
String str, cword = "", maxword = "";
int len, maxlen = 0, clen = 0, i;
char ch;
System.out.print("Enter the sentence: ");
str = sc.nextLine();
str = ' ' + str;
len = str.length();
for (i = 0; i < len; i++)
{
ch = str.charAt(i);
if (ch != ' ')
{
cword = cword + ch;
}
else
{
clen = cword.length();
if (clen > maxlen)
{
maxlen = clen;
maxword = cword;
}
cword = "";
}
}
System.out.println("The longest word is: " + maxword);
System.out.println("The number of characters in it: " + maxlen);
}
}
Thanks!!
KimChinkyo:
thank you so much friend!
Answered by
4
Hope it helps!!!....
Attachments:
Similar questions
Business Studies,
8 months ago
Hindi,
1 year ago