我需要这个程序来查找Java中String中最长的单词

时间:2016-12-24 04:26:56

标签: java java.util.scanner

import java.util.*;
class Exam3
{
      public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a String: ");

    String word1 = "", word2 = "";
    int l1 = 0, l2 = 0;

    while(sc.hasNext())
    {   word1 = sc.next();
        l1 = word1.length();
        if(l1 > l2)
        {
            l2 = l1;
            word2 = word1;
        }
    }

    System.out.println("Longest Word: " + word2);
    System.out.println("Length of Word: " + l2);
}
}

代码不起作用。提示用户成功,但没有其他事情发生。如果您输入一个字符串并按Enter键,它将转到下一行,您可以再次输入等等。

2 个答案:

答案 0 :(得分:2)

循环中应该有一个退出条件。请使用以下代码。

import java.util.Scanner;

public class LongestString {

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

        System.out.print("Enter a String: ");

        String word1 = "", word2 = "";
        int l1 = 0, l2 = 0;

        while (sc.hasNext()) {
            word1 = sc.next();

            // type exit finish the loop
            if (word1.equals("exit"))
                break;

            l1 = word1.length();
            if (l1 > l2) {
                l2 = l1;
                word2 = word1;
            }
        }

        sc.close();

        System.out.println("Longest Word: " + word2);
        System.out.println("Length of Word: " + l2);
    }
}

答案 1 :(得分:0)

这种方法对我有用

public class actual {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a String: ");

        int largestLength = 0;
        String largestWord = "";
        String a = sc.nextLine();
        for(String b:a.split(" ")){
            if (largestWord.length() == 0) {
                largestLength = b.length();
                largestWord = b;
            } else if (b.length() >= largestLength) {
                largestLength = b.length();
                largestWord = b;
            }
        }
        sc.close();
        System.out.println("Longest Word: " + largestWord);
        System.out.println("Length of Word: " + largestLength);
    }
}