Skip to content
Advertisement

Java: Count duplicate tokens on line using Scanner object

Yes this is an exercise from “Building Java Programs”, but its not an assigned problem.

I need to write a method that reads the following text as input:

JavaScript

And produces the following as output:

JavaScript

Now I know I have to use Scanner objects to first read a line into a String, the to tokenize the string. What I don’t get is how I read a token into a string, then immediately compare it to the next token.

CONSTRAINT -> This is from the chapter before arrays so I’d like to solve without using one.

Here is the code I have so far:

JavaScript

Advertisement

Answer

No need to use arrays…you just need a little bit of state in the while loop:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement