While loop Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • WeiNg

    While loop Problem

    Code:
            int AmtOfQuotes = 1;
            //A bit of help? The ! at the front means not.
            while (!Quotes[AmtOfQuotes].equals("")){
                AmtOfQuotes++;
            }
    
            AmtOfQuotes--;
    These are my code (part). When i compile my whole program, i get:
    Exception in thread "main" java.lang.NullP ointerException
    at QuoteGenerator. main(QuoteGener ator.java:40)
    Java Result: 1

    Can someone help me?
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    Are you sure 40th line in QuoteGenerator. java is same as the post you have posted here.?

    Regards
    Dheeraj Joshi

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      I'm guessing it's complaining that there is no Quotes[1], so calling that translates to NULL and thus can not be used as a string.

      You need to make sure there is actually an element at the position you are asking for before you try to fetch it. - Simplest way to do that is to compare the index you are trying to fetch to the Array.length property. In your case that would read something like:
      if(AmtOfQuotes < Quotes.length)

      Also consider that Java arrays are zero-indexed, so when you as for Quotes[1] you are actually asking for the second element. If you want to read the whole array, you need to start with 0.

      Comment

      • Dheeraj Joshi
        Recognized Expert Top Contributor
        • Jul 2009
        • 1129

        #4
        If it has some issues with the array indexes it should throw ArrayIndexOutOf Bound exception. Not a null pointer exception.

        I guess the value at
        Code:
        Quotes[1]
        is null.

        I suggest you to display all the values in the array or if you are using any editors (like eclipse) please follow the value of array during array traverse.

        An Atli is right Array in Java is Zero indexed. So you may need to fine tune your loop.

        Regards
        Dheeraj Joshi

        Comment

        Working...