以下是代码示例:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个句子:");
String sentence = input.nextLine();
// 将句子分割成单词数组
String[] words = sentence.split("\\s+");
int maxLength = 0;
int index = 0;
for (int i = 0; i < words.length; i++) {
if (words[i].length() > maxLength) {
maxLength = words[i].length();
index = i;
}
}
System.out.println("最长的单词是:" + words[index].substring(0, maxLength));
}
}