Conf3tti Conf3tti - 14 days ago 5
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(System.in);

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 = scanner.next();
w = scanner.next();
e = scanner.next();
r = scanner.next();
t = scanner.next();

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

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

String largerString = q;
if(w.length()>largerString.length())
{
    largerString = w;
}
if(e.length()>largerString.length())
{
    largerString = e;
}
if(r.length()>largerString.length())
{
    largerString = r;
}
if(t.length()>largerString.length())
{
    largerString = t;
}
System.out.println(largerString);
Comments