Loop 需要一个输入,而它应该遍历先前输入的每个单词
Loop expects an input, while it should've iterated through every word of previous input
需要将以元音开头的每个单词更改为最长的一个。一切似乎都很好,但是当我进入它时,遇到了来自循环的意外行为 - 扫描仪需要输入(第 7 行)。它不要求输入,而是应该遍历我之前设置的句子(第 2 行)中的每个元素(单词)。我假设我错过了一些东西。
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
需要将以元音开头的每个单词更改为最长的一个。一切似乎都很好,但是当我进入它时,遇到了来自循环的意外行为 - 扫描仪需要输入(第 7 行)。它不要求输入,而是应该遍历我之前设置的句子(第 2 行)中的每个元素(单词)。我假设我错过了一些东西。
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