Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2005

Tip: Looking for answers? Try searching our database.

constructor and null pointer

Thread view: 
Michael - 06 Nov 2005 00:32 GMT
Hello, I am trying to figure out what this means. Can anyone tell me what I
am doing wrong. I have looked at this code for over a day and I get this
msg. I must be missing the idea of constructors. I thought constructors just
initiliaze the state of an object(fields). And once the object is
initialized; don't you have access to iterate through a string with the
field that was initialized. So far I can get my objects created, and return
a reference to the object; but then I can't iterate through the string. I
have absolutely no idea, what I am doing wrong. IF anyone could please help
that would be great!

Instantiating two MyString objects.
Objects instantiated.
Testing getString() returns the string: passed
Exception in thread "main" java.lang.NullPointerException
       at MyString.noMore(MyString.java:60)
       at TestMyString.main(TestMyString.java:41)
Press any key to continue . . .
Andrew Thompson - 06 Nov 2005 01:02 GMT
> Hello, I am trying to figure out what this means. Can anyone tell me what I
> am doing wrong. ..

It is apparenlty an error in your code, which
first becomes *apparent* at..

> Instantiating two MyString objects.
> Objects instantiated.
> Testing getString() returns the string: passed
> Exception in thread "main" java.lang.NullPointerException
>         at MyString.noMore(MyString.java:60)

..at line 60 of MyString.  Thought it might be caused
by a null parameter that something in or before..

>         at TestMyString.main(TestMyString.java:41)

..was supposed to initialise, but did not.

It is hard to be more specific without the code you
are using, preferably short and complete..
<http://www.physci.org/codes/sscce.jsp>
[ Note that unless the code is complete, it is very
difficult to align the line numbers given in errors,
with the corrseponding code statements. ]
Roedy Green - 06 Nov 2005 07:20 GMT
>Exception in thread "main" java.lang.NullPointerException

See
http://mindprod.com/jgloss/runerrormessages.html#NULLPOINTEREXCEPTION

Without seeing your code, I can't do anything but hand out generic
advice.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Michael - 06 Nov 2005 18:12 GMT
Hello, thanks guys for the input. I know its kind of hard to help when you
can't see the code, so here it is.

public class MyString {

     // fields
 private int i = 0;
 private char ch;
 private String str;
 private boolean a = true;

    // methods

    // This method resets the index used to iterate through the string
    public void resetIndex() {
 i = 0;
 }

    // This method returns the reference to the string currently being
    // iterated through
    public String getString( ) {

         //*****

        // this return statement will need to be modified
        //System.out.println(a);
        return str;
    }

    // This methods returns the character at the current index and
    // increments the index
    public char nextChar( ) {

  while(i < str.length()) {
  ch = str.charAt(i);
  return ch;
  }
  i = i + 1;

  if(i == str.length()) {
   ch = '0';
   return ch;
  } else {
   ch = str.charAt(i);
  }

   return ch;
 }

    // This method returns true if the index is greater than the position
of
    // the last character in the string.  Otherwise, it returns false.
    public boolean noMore( ) {

  if( i == str.length()) {
   return true;
  }

  else if(i != str.length()) {
  }
   return false;

        // this return statement will need to be modified

    }

    // constructors
    // this constructor takes initializes the object with the String s
    // which will be iterated through
    public MyString( String s ) {
  //System.out.println(s);
  i = 0;
  str = s;
  if(s==null) {
   throw new NullPointerException();
  }

  //System.out.println(str);

 }
}

I am getting an runtime error. Here is the error
Exception in thread "main" java.lang.NullPointerException
       at MyString.<init>(MyString.java:88)
       at TestMyString.main(TestMyString.java:73)
Press any key to continue . . .
I have used println calls throughout the program to try to find the problem;
however, not any luck yet. Well if someone can see see something obivious;
please point it out. Thanks again in advance.

>>Exception in thread "main" java.lang.NullPointerException
>
[quoted text clipped - 3 lines]
> Without seeing your code, I can't do anything but hand out generic
> advice.
Andrew Thompson - 06 Nov 2005 22:01 GMT
> Hello, thanks guys for the input. I know its kind of hard to help when you
> can't see the code, so here it is.

OK here is where it gest tricky.
1st did you read the article on the SSCCE?

The reason I ask is that after adding a main to
your code to make it runnable, I tried instatiating
two MyString's and printing them, worked just fine.

This suggestst the problem is in the earlier source,
as I'd alluded to in my initial post.

Now please read the SSCCE document, and post an SSCCE*.

[ * Alternately, make a clear statement that you don't
have time to read the documents I recommend. So we at
least know where you're at. ]
Michael - 06 Nov 2005 23:07 GMT
Hello, I will defiently read those documents. But for the time being; that
is time remaining I don't really have the time to throughly go through those
SSCCE documents. As a full course load requires much time. I have got my
code to pass everything. Except I keep getting that nullPointer exception
for the  noMore () method. I realize at this point in this method str. is
longer pointing to an object. But I am unsure how to fix that. I am still
struggling with the big picture of OO; atleast I feel that way. Anyways
thanks for the input.

>> Hello, thanks guys for the input. I know its kind of hard to help when
>> you can't see the code, so here it is.
[quoted text clipped - 14 lines]
> have time to read the documents I recommend. So we at
> least know where you're at. ]
Andrew Thompson - 06 Nov 2005 23:25 GMT
> Hello, I will defiently read those documents. But for the time being; that
> is time remaining I don't really have the time to throughly go through those
> SSCCE documents. As a full course load requires much time.

A 'full course load' will be a lot fuller if you require
twice as many posts on usenet to solve a given problem.

The SSCCE helps you to presenet the information required
to allow others to spot the technical problem in the first
post.

Even better, the process of preparing an SSCCE often
*solves* the problem.

Let me know when you've had time to read it, I'll
be prepared to look more closely at your problems
after you start supplying SSCCE's.

Otherwise - *I* don't have the time to make up for
your time deficiencies.
Roedy Green - 06 Nov 2005 23:54 GMT
>But for the time being; that
>is time remaining I don't really have the time to throughly go through those
>SSCCE documents. As a full course load requires much time. I have got my
>code to pass everything.

I don't think you understand how rudely that comes across.  You are
saying "Your time is valueless, mine precious."

"It is perfectly ok for me to waste your time so long as it saves me
time."

You can't be expected to follow all the advice that every experienced
person gives you, but you have to be careful about tossing it back in
his face without even looking at it.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Michael - 07 Nov 2005 00:05 GMT
Okay, sorry guys if I offended you; I did not mean too. That insight must
have went right over my head, as with the programming part. I'll look into
the documents more throughly before posting again. SOrry for the
inconivence.

>>But for the time being; that
>>is time remaining I don't really have the time to throughly go through
[quoted text clipped - 11 lines]
> person gives you, but you have to be careful about tossing it back in
> his face without even looking at it.
Michael - 07 Nov 2005 03:23 GMT
Ok guys, I've read the documentation. My problem is I am receiving a null
pointer exception. I have searched to find an answer for this question and
came up with the idea that; this reference is not pointing to an object. I
get the following run time error;

Exception in thread "main" java.lang.NullPointerException
       at MyString.noMore(MyString.java:67)
       at TestMyString.main(TestMyString.java:74)
Press any key to continue . . .
The part of code causing this problem is the following;

public boolean noMore( ) {
if( i == str.length()) {
   return true;
  }else if(i != str.length()) {
  }
   return false;

In my testString class the line of the code complaining is;
pass = m.noMore() && (m.nextChar() == 0);
I am returning a boolean value of true in the former case if
i==str.length(), and a false if i !=str.length(). Somehow the reference to
the object(str) is becoming dereferenced. I just don't how to cure this
problem. I have tried to introduce a variable before the if clause to accept
the length's value. Then I inserted that into the the clause. For example, I
did the following;
int test = str.length()
if(i==test){
return true;
}else
}
return false;
I hope this is correct to meet the document liking. Thanks again.

> Okay, sorry guys if I offended you; I did not mean too. That insight must
> have went right over my head, as with the programming part. I'll look into
[quoted text clipped - 16 lines]
>> person gives you, but you have to be careful about tossing it back in
>> his face without even looking at it.
Thomas Hawtin - 07 Nov 2005 04:01 GMT
> Exception in thread "main" java.lang.NullPointerException
>         at MyString.noMore(MyString.java:67)
[quoted text clipped - 8 lines]
>    }
>     return false;

You don't say which is line 67. Looks as if str is null. Is it?

It's somewhat difficult to say what the exact problem is without a
small, self-contained, compilable example thingy.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/

Michael - 07 Nov 2005 04:42 GMT
Hello I tried to validate my code with HTML validator,CSS validator, JSLint,
and JOCL; but I get an error everytime I try to validate it. None of the
these will allow me to format my code to be viewed on the newsgroup. WHy is
that, is there anything else I can do. I am using textPad with word Warp
turned off.  And yes
line 67 is indeed the following line;
if(i == str.length())
Thanks again.

>> Exception in thread "main" java.lang.NullPointerException
>>         at MyString.noMore(MyString.java:67)
[quoted text clipped - 15 lines]
>
> Tom Hawtin
Andrew Thompson - 07 Nov 2005 04:59 GMT
> Hello I tried to validate my code with HTML validator,CSS validator, JSLint,
> and JOCL; but I get an error everytime I try to validate it.

My apologies.  The Java-On-Line Compiler (the only one
applicable here) isn't (on-line).

The basic concept boils down to code, that when you
copy/paste it from usenet to an IDE/editor, will
compile and run to display the problem.

Check the groups for code posted in between
<sscce>
...the code...
</sscce>
..for actual examples, but most of the code in the Sun
tutorials is also written to be 'small and self contained'.
Andrew McDonagh - 07 Nov 2005 23:18 GMT
For the love of god Micheal - just post all of your damn String class
code so we can look at it directly.

you are giving us teeny-tiny pieces of a large jig-saw and asking to
tell you what the picture is!

as it is, if the exception says 'nullpointerException on line 67' then
look at line 67!

See what objects have method calls being performed on them - this object
will be the one that is null.

Once you know what object it is, then you can put a break point on the
line and debug your code.

debugging via usenet will take longer the universe has time left.

> Hello I tried to validate my code with HTML validator,CSS validator, JSLint,
> and JOCL; but I get an error everytime I try to validate it. None of the
[quoted text clipped - 24 lines]
>>
>>Tom Hawtin
Bjorn Abelli - 07 Nov 2005 11:12 GMT
"Michael" wrote...

> I get the following run time error;
>
[quoted text clipped - 13 lines]
> In my testString class the line of the code complaining is;
> pass = m.noMore() && (m.nextChar() == 0);

Which don't make much sense...

It looks like a condition of some sort, but badly constructed.

Do you know what it means?

It looks like it's composed of two parts

  pass = m.noMore()

  &&

  m.nextChar() == 0

The first one assigns a boolean value from the result of m.noMore(). As such
this part of the condition will also have that value (true or false).

The second part compares the "next character" with the numeric value of
zero. As a "char" is a numeric value, it's a valid condition, but it's not
likely that it actually returns that...

Maybe you really wanted to compare with the *character* zero instead?

  m.nextChar() == '0'

> I hope this is correct to meet the document liking.

Nope, you've not provided enough code from you "testString" for us to see
how it instantiates and manipulates the MyString.

BTW, there are some logical flaws in your class MyString as well. nextChar
will always return the first character of the string, as it never actually
increments i...

// Bjorn A
Roedy Green - 07 Nov 2005 11:49 GMT
On Mon, 7 Nov 2005 12:12:35 +0100, "Bjorn Abelli"
<bjorn_abelli@DoNotSpam.hotmail.com> wrote, quoted or indirectly
quoted someone who said :

>> public boolean noMore( ) {
>> if( i == str.length()) {
>>    return true;
>>   }else if(i != str.length()) {
>>   }
>>    return false;

you could write that more concisely as:

 public boolean noMore() { return i == str.length(); }

i should be reserved to use in a for loop.  Using it in other contexts
is not a good idea because of the presumption i is the for index based
on an idiom dating back to FORTRAN.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Monique Y. Mudama - 08 Nov 2005 22:32 GMT
> I am getting an runtime error. Here is the error Exception in thread
> "main" java.lang.NullPointerException at
[quoted text clipped - 3 lines]
> the problem; however, not any luck yet. Well if someone can see see
> something obivious; please point it out. Thanks again in advance.

Consider using a debugger, such as the one eclipse provides.  I tend
to prefer print outs and turn to the debugger as a last resort,
myself, but I think you can probably solve this problem handily by
stepping through your code line by line until it blows up.  Then you
know exactly what happened and the path your code followed.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.