Loop expects an input, while it should've iterated through every word of previous input

Viewed 51

Need to change every word, that starts with vowel to the longest one. Everything seems ok, however have faced with an unexpected behaviour from the loop, when I enter into it - scanner wants an input (7th line). Instead of asking for an input, it should iterate through every element (word) from the sentence I've set previously (2nd line). I do assume, that I've missed something.

    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;
    }
1 Answers

By looking at your code, I see you are trying to find the longest string in a sentence inputted by user.
There is no need to input every word individually when you simply could input the entire line. Something like the following code could help you:

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));
    }
}

When run with input Find the longest word in this large sentence this outputs:

Input a sentence: 
Find the longest word in this large sentence.
Longest word is sentence
Related