Monday, May 24, 2010

How do you have java read a passage from a text file and pick out the isograms?

An isogram is a word that has no repeating letters in it (ie. "computer" is an isogram where "science" is not.)





I need help with this...i need to know how for a future java project. Better to get familiar with this now than later...

How do you have java read a passage from a text file and pick out the isograms?
I'll just give you an outline for how I'd do it to start, but if you have a question while writing the code, I'd be happy to help out. Just ask away.








To start, read in the entire file. Use String.split() to split the different tokens (i.e., words) over whitespace characters. This will put each token as an element of an array. Then loop through that array, like so (straight from Java docs):





String[] result = "this is a test".split("\\s");


for (int x=0; x%26lt;result.length; x++)


System.out.println(result[x]);





Here's the not-so-straightforward part. Within that loop, you need to verify the token is an isogram. (To shorten code, you could write a separate function isIsogram() that returns a boolean.) I first thought I could make a boolean array of size 255 and then put 'true' to the array index of the ASCII value of the current character, then check each time if that space is already true. That should work, but it seems a bit contrived and a waste of space. Instead, I figure you could use some sort of List object, like a LinkedList. That would be stupid easy:





You would loop through a string character by character, and for each one, add it to the list (LinkedList.add()). Then each time, check and see if it already contains that characters (LinkedList.contains()). If it does, it's not an isogram. If you make it through the loop without that happening, it is an isogram. After you finish a word and are ready to move on to the next, empty the list (LinkedList.clear()). Stupid easy, right?





Obviously, when you find an isogram, add it to a list or array. (I would go with LinkedList again, since you won't know how many words you'll have until you're finished. It's variable in size, while you must specify the size of an array.) When all is said and done, loop through the list of words, printing them out or doing whatever.








Hopefully that was all clear enough to get you started. Like I said, feel free to ask for help if you need it while coding that up. Good luck!


No comments:

Post a Comment