I need to write a program that takes in a string from a user and finds the longe
ID: 3644836 • Letter: I
Question
I need to write a program that takes in a string from a user and finds the longest word in the string.So far i have....
import java.util.Scanner;
public class Lab2_new {
public static void main(String[] args)
{
String sentence;
String word;
String longest = "";
System.out.print("Enter sentence: ");
sentence = inputLine.readLine();
Scanner keyboard = new Scanner(sentence);
while (keyboard.hasNext())
{
word = keyboard.next();
if (word.length() > longest.length())
{
longest = word;
}
}
System.out.println("The longest word is: " + longest );
}
}
Ive tried it using a bufferedreader, inputstreamreader, and IOexception which words but we technically haven't learned those yet so i need a code without but i can't seem to get it right
Thank you!
Explanation / Answer
Scanner sc = new Scanner( System.in ); String line; String largest; String currentWord; String wordsInLine[]; System.out.println("Input a line of text."); line = sc.nextLine(); line = line.trim(); if (line.equals( "" )) { System.out.println("You have not entered a line with words."); return; } wordsInLine = line.split(" "); largest = wordsInLine[0]; for (int i = 1; i largest.length()) { largest = currentWord; } } while (true) { System.out.println("Input another line of text."); line = sc.nextLine(); line = line.trim(); if (line.equals( "" )) { System.out.println("You have choosen to stop inputting lines."); break; } wordsInLine = line.split(" "); for (int i = 0; i largest.length()) { largest = currentWord; } } } System.out.println( "The largest word is " + largest + " It has a length of " + largest.length);Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.