|
-
April 14th, 2010, 03:49 PM
#1
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?
-
April 15th, 2010, 05:52 AM
#2
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
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
-
April 16th, 2010, 11:27 AM
#3
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!
-
April 16th, 2010, 12:10 PM
#4
Re: Variable Wont increment in while loop
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|