CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2010
    Posts
    4

    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?

  2. #2
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    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.

  3. #3
    Join Date
    Apr 2010
    Posts
    4

    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!

  4. #4
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    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 code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured