Variable Wont increment in while loop
Howdy, very new to java programming. I am reading in a text file from my computer and attempting to store it in an array of strings, one word per string. However, they all appear to be in the first string of the array. wordCount++ wont increment so I am able to store the strings in different spots in the array.
public void processLine(String aLine){
int wordCount = 0;
String[] wordList = new String [100];
Scanner scanner = new Scanner(aLine);
while( scanner.hasNext()){
String name = scanner.next();
wordCount++;
System.out.println("wordCount is " + wordCount);
wordList[wordCount] = name;
System.out.println("Value is " + wordList[wordCount]);
}
Any ideas?
Re: Variable Wont increment in while loop
Please post code inside [CODE]...[/CODE] tags to retain formatting so we can read it.
There's nothing wrong with that code, it works fine for me. Are you certain that you're passing a valid line to it? Why not put a print statement at the beginning to check.
Incidentally, a simpler way to get an array of words from the line is to use String.split(..), e.g:
Code:
String[] wordList = aLine.split(" ");
The best writing is rewriting...
E. B. White
Re: Variable Wont increment in while loop
Hey Thanks! I dont know why my wordCount variable wasn't working, but String[] wordList = aLine.split(" "); did the charm. Thanks!
Re: Variable Wont increment in while loop
Quote:
I dont know why my wordCount variable wasn't working
No, it is working. I suspect the problem is your input string isn't being split into individual words as it doesn't contain valid whitespace characters.
What you have got wrong is you are incrementing the counter too early and so are storing the first word in element 1 rather than element 0.