Gordislan
Gordislan

Reputation: 11

Problems with counting spaces - Java

I'm having problems with the code below. It asks for the user to type in a sentence basically.

System.out.println("Enter a string containing spaces: ");
inputString = keyboard.next();
int lengthString = inputString.length();

System.out.println("You entered: " + inputString + "\n" + "The string length is: " + lengthString);

The problem is when it prints the statement, it only prints the first word, then counts the characters contained within the first word. I'm really new to Java, so I was wondering what should I do to make the program count the WHOLE string.

Upvotes: 1

Views: 122

Answers (2)

user1231232141214124
user1231232141214124

Reputation: 1349

keyboard.nextLine() will pull in the entire line. next() only gets the next word. next() uses spaces by default to determine word sizes, but you can also set a custom delimiter if you want it to pull in different tokens.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213411

You should use nextLine() method instead of next():

inputString = keyboard.nextLine();  

Scanner#next() method reads the next token. Tokens are considered to be separated by a delimiter. And the default delimiter of Scanner is as recognized by Character.isWhitespace.

Upvotes: 5

Related Questions