查找并比较字符串

时间:2016-09-15 00:20:54

标签: java

所以我需要编写一个程序来读取五个单词的句子,找到句子中最长的单词并显示它。如果恰好有两个同样大的单词,它只显示第一个最大的单词。

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);
    }
}

你可能会告诉我卡在哪里。我真的不知道如何比较这些词。首先想到的是使用if / else来单独比较它们,使用line.length()。

不能使用数组,.split或循环(遗憾地)。

5 个答案:

答案 0 :(得分:1)

向老师展示这个!

Stream.generate(scanner::next).limit(5)
    .max(Comparator.comparing(String::length))
    .ifPresent(System.out::println);

答案 1 :(得分:0)

如果你只是想显示最大的单词,你可以按如下方式进行,如果单词数超过5,它也会是动态的。

Scanner in = new Scanner(System.in);

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

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

String maxWord = "";
while(scanner.hasNext()){
    String word =scanner.next();
    if(word.length()>maxWord.length())
        maxWord = word;
}
System.out.println(maxWord);

答案 2 :(得分:0)

鉴于约束,我建议您使用if假设的语句。

import java.util.Scanner;
public class Longest_Word {

public static void main(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();
    String longest = q;

    w = scanner.next();
    if (w.length()>longest.length())
        longest = w;

    e = scanner.next();
    if (e.length()>longest.length())
        longest = e;

    r = scanner.next();
    if (r.length()>longest.length())
        longest = r;

    t = scanner.next();
    if (t.length()>longest.length())
        longest = t;

    System.out.println(longest);
}
}

答案 3 :(得分:0)

读取列表中的所有值,并使用Java Streams查找最长的字符串

String logestStr = list.stream().max(Comparator.comparing(String::length)).get();

答案 4 :(得分:0)

如果/ else和循环对于这个问题是相同的。

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);