javaloopsif-statementdebuggingconsole-application

Trying to print second last word but output shows only "L". What's wrong with my Java code?


A program that prints the second last word of a sentence.

public class secToLast{
    public static void main(String args[]){
        String gg = "I love India";
        int len = gg.length();
        char[] word = new char[25];
        for(int i = len-1 ; i>=0; i--){ 
            if(gg.charAt(i)==' '){
                int j = i-1;       
// > trying to store the word in array
                while(j>=0 && gg.charAt(j) != ' '){
                    int k = 0;
                    word[k] = gg.charAt(j);
                    j = j-1;
                    k = k+1;
                }
                break;
            }
        }
        int wlen = word.length;
        for(int p = wlen-1; p>=0; p--){      //printing the word array in reverse
            System.out.print(word[p]);
        }
    
    }
}

the output should have been 'love' and I think something is wrong with my loop indices. If I had to guess, I think I have to use another break statement somewhere, I just need help in putting it in right place.


Solution

  • I answer your direct question, “What’s wrong with my Java code?” and suggest a fix. The fix will be described in prose only since you learn more from fixing the concrete Java code yourself.

    There are two things wrong with your code:

    1. Most importantly, in your innermost loop, the while loop, you are setting k to 0 and then saving the current letter into index k of word, that is, in index 0. So you are always overwriting the same array element. With the letters e, v, o and l in order. So the final value is l.
    2. When printing the result you are using the length of the array, so 25 regardless of the length of the word you have found. Since a char array is initialized to hold \0 characters, 24 of these are printed before the l.

    I am assuming that k was meant to be the number of letters in the word. Really, you need better variable names, like wordLength or letterCount. Staying with the name k for now I suggest that you should declare and initialize k before your first for loop. Then when you increment k in the inner loop (which you already do), the letters will be stored into consecutive array elements. Why I suggest you declare k already before for is then you still have it when printing so instead of printing the entire word array you can print only k elements of it (em dash deleted since it seems to have offended some) the word found.

    Another tip, learn to use a debugger.