Conf3tti Conf3tti - 1 year ago 77
Java Question

Find and compare lengths of individual words in a string

So I need to write a program that reads a sentence of five words, and finds the longest word in the sentence and displays it. If there happen to be two equally large words, it just displays the first largest word.

import java.util.Scanner;

public class Longest_Word {

public static void main(final String[] args) {
Scanner in = new Scanner(;

String line;
String q, w, e, r, t;

System.out.print("Enter a five word sentence: ");
line = in.nextLine();
Scanner scanner = new Scanner(line);

q =;
w =;
e =;
r =;
t =;

System.out.println(q + " " + r);

You can probably tell where I'm stuck. I really don't know how to compare these words. The first thing that came to mind was to use if/else to compare them individually, using line.length().

Can't use array, .split, or loops (sadly).

Answer Source

if/else and loops are the same for this problem.

String largerString = q;
    largerString = w;
    largerString = e;
    largerString = r;
    largerString = t;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download