Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Read words from the keyboard for as long as the input lasts. When there is no mo

ID: 3754063 • Letter: R

Question

Read words from the keyboard for as long as the input lasts. When there is no more input print out the length of the longest word and the longest word.

For instance if the user types "a b c this is getting long extremely long" you would output "Longest word has 9 characters. The word is "extremely"."

Make sure to use Scanner's hasNext() function to read from keyboard only while there is input available. That way your program won't crash.

Explanation / Answer

import java.util.Scanner; public class LongestWordWithLength { public static void main(String[] args) { Scanner in = new Scanner(System.in); String longest = "", str; while (in.hasNext()) { str = in.next(); if(str.length() > longest.length()) { longest = str; } } System.out.printf("Longest word has %d characters. The word is "%s". ", longest.length(), longest); } }