The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.



Posted by Matt Gerrans on November 26, 2001 at 3:53 PM

Maybe a couple of tips will help bring it into the realm of possibility for you:

  • Why are you reading one character at a time? Are you opposed to using a BufferedReader?
  • Even if you do read one char at a time, what's to prevent you from assembling strings from those chars?
  • Furthermore, even if you read in one char at a time and don't build any strings, you can still keep count of word lengths easily enough -- just count chars until the next whitespace.
  • If you can post the code you wrote, maybe some more pointers can be proffered.
  • It is never too early to start good programming habits, so rather than couple your program to the keyboard, you should make it able to handle a string or buffer from any source, not just the keyboard. That way, when the next assignment is to write a program that analyzes text files, you are already done. (It works this way in real life, even better).

Somehow, I don't think this program ranks among the more challenging endeavors attempted in software development, so "impossible" my be just a bit of overstatement.

- mfg

> I have been asked the following question to solve can anyone help!!

> Assuming that a sentence consists of a sequence of words separated by single spaces and terminated by a full stop, write and implement a Java program that will read in a sentence from the keyboard and will print out each word on a separate line together with the number of letters in each word. For example:

> Mary had a little lamb.

> Mary 4
> had 3
> a 1
> little 6
> lamb 4

> The sentence should be short enough to be entered on one line of input. It should be treated as a sequence of characters, which may be read in one at a time. Each character must be either a letter or a space or a full stop. The program will not start reading the characters until the sentence is terminated and the ENTER key is pressed. The first digit of the number of letters in each word should be vertically aligned and you may assume that no word will be longer than 20 characters.

> I tried to get a solution myself but if you read in it as character you can't read the length of each word that is to be returned. If anybody has a solution please respond as I am in great difficulty here!!

> Thanks
> A distressed programming student.


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us