询问用户输入(句子)并打印出该句子中最长的单词

时间:2015-03-18 01:55:38

标签: java eclipse

如何让这个程序询问用户输入(一个句子)并打印出该句子中最长的单词。

package projectOne;

import java.util.Scanner;

public class LongestWord {

//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();

static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");

public static void main(String [] args){


    Scanner keyboard = new Scanner(System.in);
    System.out.println("In 1 sentence tell me what is on your mind today.");
    //String actualstring = keyboard.nextLine();
    //String[] splitstring = actualstring.split(" ");

    LongWord();

}

public static void LongWord() {     
    String longword = "";
    for (int i=0; i<=splitstring.length-1; i++){    
    if (longword.length()<splitstring[i].length())
        longword = splitstring[i];  

    }


    System.out.println(longword);
    int replyLength = longword.length();
    System.out.println(replyLength);

    if (replyLength == 3)
        System.out.println("Hmmm tell me more about "+longword+" please");
    else if (replyLength == 4)
        System.out.println("Why do you feel "+longword+" is important?");
    else if (replyLength == 5)
         System.out.println("How does "+longword+" affect you?");
    else if (replyLength > 5)
         System.out.println("We seem to be making great progress with "+longword);
    else
        System.out.println("Is there something else you would like to discuss?");

   }


}

2 个答案:

答案 0 :(得分:0)

我不认为您非常了解方法的运作方式。在您的主要内容中,您应该提示用户输入他们想要输入的行,然后您应该使用Scanner.nextLine()方法读取整个行String,然后您应该传递所述{{ 1}}进入你的longWord方法进行处理。

String

答案 1 :(得分:0)

尝试:

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    String maxword = null;
    str = str + ' ';
    int l = str.length();
    String word = "";
    int maxlength = 0;
    for (int i = 0; i < l; i++) {
        word = word + str.charAt(i);
        if (str.charAt(i + 1) == ' ') {
            if (word.length() > maxlength) {
                maxword = new String(word);
                maxlength = word.length();
            }
            word = "";
            i++;
        }
    }
    System.out.println("Longest Word: " + maxword);

}