Search code examples
javajava.util.scannerdelimiterstring-length

Trying to get the length of a sentence from a user input but it stops after the first word and space


The Java task is to have the user type a sentence/phrase and then print out how many characters the sentence has. My .length() method is only counting the first word and space as characters. I've read previous questions and answers involving nextLine() but if I use that instead of next() it only lets the user type it's question and waits, doesn't print anything else immediately anymore. I'm brand new to Java and I think this can be fixed with a delimiter but I'm not sure how or what I'm missing. TIA!!

Update: Here's my code.

import java.util.Scanner;

class StringStuff{
   public static void main( String [] args){

      Scanner keyboard = new Scanner(System.in);
      int number;

      System.out.print("Welcome! Please enter a phrase or sentence: ");
      System.out.println();
      String sentence = keyboard.next();
      System.out.println();

      int sentenceLength = keyboard.next().length();


      System.out.println("Your sentence has " + sentenceLength + " characters.");
      System.out.println("The first character of your sentence is " + sentence.substring(0,1) + ".");
      System.out.println("The index of the first space is " + sentence.indexOf(" ") + ".");


   }
}

when I type "Hello world." as the sentence it prints:

Your sentence has 6 characters. The first character of your sentence is H. The index of the first space is -1.


Solution

  • keyboard.next call is waiting for user input. You're calling it twice, so your program expects the user to enter two words.

    So, when you type in "Hello world." it reads "Hello" and "world." separately:

    //Here, the sentence is "Hello"
    String sentence = keyboard.next();
    System.out.println();
    
    //Here, keyboard.next() returns "World."
    int sentenceLength = keyboard.next().length();
    

    And when you use nextLine your code is waiting for the user to enter two lines.

    To fix this you need to:

    1. Read the whole line with nextLine.
    2. Use sentence instead of requesting user input the second time.

    Something like this should work:

    String sentence = keyboard.nextLine();
    System.out.println();
    
    int sentenceLength = sentence.length();