Search code examples
java.util.scannersentence

Ending a Scanner


I have been working on a code that reports some statistics about words in an input sentence. The code should be processing input until the i just press the enter key, but i can't get it to iterate once, i just keep hitting enter and my data won't process. I assume the issue is the way I have the 2 scanners set up. I am trying to use both scanners, but nothing I change seems to work.

import java.util.Scanner;

public class SentenceStatistics
{
    public static void main(String [] args)
  {
       Scanner kReader = new Scanner(System.in);


        System.out.print("Enter a sentence: ");
        String input = kReader.nextLine();

        Scanner wReader = new Scanner(System.in);



        int wordCount = 0;
        int sentenceLength = 0;
        int beginPosition = 0;
        int endPosition = input.indexOf(' ');

        while(kReader.hasNext())
        {
             System.out.println(wReader.next());
             wordCount++;
             String word = kReader.next();
             sentenceLength += word.length();            
             beginPosition = endPosition + 1;
             endPosition = input.indexOf(' ', beginPosition);
        }



             System.out.println("word count: " + wordCount);
             System.out.println("Sentence length: " + sentenceLength);
             System.out.println("Average word length: " + sentenceLength / wordCount);


     }


}

This should be a simple problem but I can't get it to work.

Thanks for the help, Packerfan504


Solution

  • In Java, an object stays alive as long as there is a reference to it. In your case there will always be a reference to it in the objects of class SentenceStatistics.