需要将以元音开头的每个单词更改为最长的单词。一切似乎都不错,但是当我进入循环时,它遇到了循环中的意外行为-扫描程序需要输入(第7行)。而不是要求输入,它应该遍历我之前设置的句子(第二行)中的每个元素(单词)。我确实以为我错过了一些东西。
Scanner sc = new Scanner(System.in);
String textToFormat = sc.nextLine();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(textToFormat);
while (sc.hasNext()) {
currentWord = sc.next();
if (currentWord.length() > longestWord.length()) {
longestWord = currentWord;
} else break;
}
通过查看您的代码,我发现您正在尝试查找用户输入的句子中最长的字符串。您只需输入整行,就无需单独输入每个单词。类似于以下代码的内容可以为您提供帮助:
import java.util.Scanner;
public class Main {
public static String findLongestWord(String[] arr){
String longest = "";
for (String current : arr){
// If the current word is larger than the longest.
if(current.length() > longest.length()){
longest = current; // Then set longest word to current.
}
}
return longest;
}
public static void main(String[] args) {
// Get the sentence from the user.
System.out.println("Input a sentence: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
// Split sentence into words.
String[] arr = s.split("\\W+");
System.out.println("Longest word is " + findLongestWord(arr));
}
}
[使用输入Find the longest word in this large sentence
运行时,输出:
Input a sentence:
Find the longest word in this large sentence.
Longest word is sentence