Results 1 to 2 of 2

Thread: Bit of bother

  1. #1
    Shimless12 is offline Member
    Join Date
    Jul 2011
    Posts
    12
    Rep Power
    0

    Default Bit of bother

    struggling to make a code where if the string has "ab ab acde" it would come out as "2,1" due to 2 2 letter words and 1 three letter word. at the minute I've got this:

    Java Code:
    
    int[] lengths = new int[100]; characters
    int longestWord = 0;
    for(int i = 0; i < lengths.length; i++) {
    lengths[i] = 0;
    }
    try{
    String line;
    int numTokens = 0;
    int numWords = 0;
    int numChar= 0;
    while ((line = textEntry.getText()) != null ) {
    String[] words = line.split(" ");
    numWords = numWords + words.length;
    for (int i = 0; i < words.length;i++) {
    numChar = numChar + words[i].length();
    if(words[i].length() > longestWord) {
    longestWord = words[i].length();
    }
    lengths[words[i].length()] = lengths[words[i].length()] + 1;
    }
    for(int i = 0; i <= longestWord; i++) { 
    System.out.println(i + " :"+lengths[i]);
    it appears to go into an infinite loop any help or advice appreciated thanks!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    Default

    it appears to go into an infinite loop
    Which loop is infinite?
    What values of what variables will keep the code in the loop? Use printlns to print out those values.
    Then look at the values printed out and look at your code to see where the problem is.

    Your unedited code is very hard to read to see where the end of the loops are.
    Your code needs to be edited to add indentations for nested code. The code inside of {} should be indented.
    The } should align vertically with the statement that starts the block.

Posting Permissions

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