This week's book giveaway is in the Spring forum.
We're giving away four copies of Spring in Action (5th edition) and have Craig Walls on-line!
See this thread for details.
Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

NullPointerException generated with toString method: confused as to why  RSS feed

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, really stressed, no idea what is going wrong with my code. I do not have any errors reported in the code, but the errors are generated when I run the code.



That is my (one of) my model classes, and whenever I run my code, I get an error (one of several) returned stating:

Exception in thread "main" java.lang.NullPointerException
at model.City.toString(City.java:123)



Now my (limited) understanding is that the NullPointerException occurs when an object makes reference to a null value. That in itself is confusing the hell out of me, because I thought all my fields were assigned values?
 
tony narloch
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The other odd things I've observed:

I am able to load and store/save text files without any difficulty......So long as the file I load from, is completely empty. As soon as I use a file with data in it, I get problems, which is leading me to conclude that the toString errror is now rippling through the rest of the code, causing a chain of errors...?
 
Saloon Keeper
Posts: 5144
54
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple of things that would help us help you:
  • Cut and past the entire error message into your post.
  • Wrap long lines of code to make them shorter (I get your long lines chopped off on my laptop).
  • When possible, provide a main() method so that it can be run.
  • Stub out classes that wouldn't normally be included so that it can be run (e.g. YearData).
  • Your code has too many unnecessary uses of "this.". It is only necessary to disambiguate between local and member variables of the same name.
  • Take your line 123 and break it into multiple lines and perhaps the error message will show you more specifically which variable it's crashing on.
  • Where you declare your member variables you can initialize them there so that they are never null, so, if they still end up null then it's due to a call to one of the constructors.
  • Perhaps add a validate method to do some basic validation of your class data.
  •  
    Sheriff
    Posts: 5446
    147
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When you say, I get errors, pick one, detail the situation in which it occurred, and post the entire error message, stack trace and all.  I know you have had many errors, but if we focus on one we will have a much better chance of success.
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    My initial suspicions seemed to have been correct.

    The error code(s) in full is as follows:



    I have narrowed the issue down further.



    If I comment out the:


    The code seems to work as it should with a new file generated and saved with the specified name, and if I add .txt at the end of the file, it is saved as a text file. Selecting option E/e results in the following output:



    All on one line. So it seems that the for loop (or perhaps more specifically, the therein contained it is posing the problem, but I am not sure why, there is no error listed for it....


     
    Knute Snortum
    Sheriff
    Posts: 5446
    147
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Is it possible that yearDataCollection is null?
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ok, I understand now that the YearDataCollection is Null.

    However, I do not know how to properly initialize it.

    My confusion stems from the fact that the values intended for the yearData is stored in a seperate class.

    the YearData class does not possess an ArrayList, only variables.



    the City class contains an ArrayList.

    The NullPointerException is being generated by virtue of the fact that the ArrayList is not initialized.

    https://imgur.com/a/HjZnI7a

    I have been trying to follow the directions/requirements of that class diagram, I realise that the solid diamond means that there is composition being used.

    Composition as I understand it: class2 dies/lives with class1. If class1 dies, so does class2.

    I thought that perhaps I was to import each of the variables of the YearData class into the City class, but this does not seem to be supported by the Class Diagram, or my course notes.

    I thought perhaps I could use ENUM to import the data, but that does not correspond to the class diagram.

    I am utterly lost here.

     
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:. . . class2 dies/lives with class1. If class1 dies, so does class2. . . .

    We are dealing with objects, not classes. Object2 constitutes a part of object1.
    There are various grades of composition, association and aggregation. Car→Engine is composition. Not only is an engine a part of a car, but it is an essential part; a car without an engine ceases to be a car in the fullest sense of the word.
     
    Knute Snortum
    Sheriff
    Posts: 5446
    147
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:the YearData class does not possess an ArrayList, only variables.


    If those variables are defined outside of any method, they are instance variables and should accessed through "getters".

    the City class contains an ArrayList.


    That makes sense.  A City would have YearData, if by that you mean annual weather patterns.  The class should be named something more descriptive, like AnnualWeather.

    If List<YearData> is an instance variable (it should be), you will need an instance of the class (an object) to access it.  You initialize it in City.


     
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator



    From that line of code, same applies to the rest of the code, I can't get clues what yearDataCollection represents. Only by seeing other talks, I got some hint that it is weather data. So something is off here. First - variable name. yearDataCollection? yearlyDataCollection, that's bad too. earlyWeatherData, reads way better. Anyway, I don't agree that city needs to know that. City has an id, so that's something unique, at least supposed to be.

    So, aren't meteorogical services provide such information given city id? That would make more sense to me.

    Experiment. That way you'd separate city from the weather data. City would be more concise and not polluted with something it shouldn't know directly in my opinion.

    Anyway, what was the task in general?
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The task is split into various increments.
    1. Load city weather data from a file and list in id order
    2. Persist city collection to a file

    As to the names, I am merely going with what the instructions are.
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Why you have so many constructors? Half of the source file are constructors. They don't make sense to me. Sometimes you can pass on ID to the city, sometimes it gets assigned automatically. So by letting to pass ID manually, how you'll ensure that different city doesn't have such ID allocated already? So I see you have a check of some kind, but it doesn't make sense. It is pointless move as anyway next ID after the latest gets assigned.

    City has so many ways to be created that it is so confusing, you need to go through each of constructors to understand what they do. Do you know this(...) concept how to invoke overloaded constructor? Anyway, I think you don't need more than 1 constructor. They simply pollute class with extra complexity without any visible benefit in my opinion. You don't validate passed parameters, so basically each of the constructors can create object in a fuzzy state.
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Again, we were given a class diagram, and we are expected to do it in a particular way (the multiple constructors being one).
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:Again, we were given a class diagram, and we are expected to do it in a particular way (the multiple constructors being one).


    Can you show us this diagram? "(the multiple constructors being one)" <-- please explain what do you mean by that?
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    This is your no-args constructor. It has CityNameComparator. Other constructors don't have. Why is like that? A bit weird name for that field (which supposed to start lower case).
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Here is the diagram

    https://imgur.com/a/cb2gQIJ
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Make class final, unless you are planning to extend it. Hardly possible scenario. So make it final.
    Make all fields final unless you are planning to re-assign them. city name won't change, country won't change. Non of them need to be re-assigned after object gets created, maybe with an exception of yearDataCollection (which is a poor name). Adding final keyword improves readability significantly, because right from the beginning of the source file you know, that such fields won't change over the time, so you don't need to track their values later in a file.

    Start small in general, don't write so many code without revising it whether it makes sense.
     
    Campbell Ritchie
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Liutauras Vilda wrote:. . . This is your no-args constructor. . . .

    It appears to initialise your fields to values you don't actually want. Why?

    I think your best approach to that constructor is to delete it. Multiple constructors simply constitute opportunities for things to go wrong, as Liutauras has already told you.
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:Here is the diagram

    https://imgur.com/a/cb2gQIJ


    Probably the course material is from very old ages, as many of the things just don't make sense in that diagram, i.e.: starting from the suggested class name YearData, then several constructors in other class, which at least 2 of them are wrong most likely.
    Why YearData supposed to have EOLN, QUOTE. Going that way need to add, COMMA, DOT, PERIOD, SEMI_COLON, COLON, and the rest of... toString(delimiter: Character) also very questionable idea, would think confusing, had to double check documentation if I'm not missing anything.

    Basically that is a poor assignment altogether in my opinion. If I were in your place, I'd speak with the tutor, whether at least you can improve things from your side without losing any functionality. The thing is, if you just go blindly with what is pushed on you, you kind of don't keep brains stretched and not thinking if there are better ways. Maybe to train yourself with mechanics of the language is useful to some extent with such exercise, but not so much outside that.
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Guys, this is exactly my dilemma. I did a similar program before, where we didnt use an interface, where we didnt have a class diagram, we pretty much had free reign to code as we saw fit. But, a way I was confident with coding with is now rendered not-allowed because I am forced to conform to a very messy and confusing class diagram. I spoke to the tutor about it, he said that we MUST follow the class diagram. So you have a coder who is not 100% confident with their skills, combined with a very poorly expressed class diagram. In short, it is a recipe for disaster.
     
    Campbell Ritchie
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:. . . we MUST follow the class diagram. So you have a coder who is not 100% confident with their skills, combined with a very poorly expressed class diagram. . . . a recipe for disaster.

    Unfortunately once an assessment has been issued, it is virtually impossible to change it. I think there are things in that class diagram I would never do.
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:I spoke to the tutor about it, he said that we MUST follow the class diagram.


    Ok, if MUST instruction have been issued, as Campbell said, you have no choice, need to stick to that.

    Sorry for questioning you so much initially and shifting from your problem at hand.

    So, what is the problem we are solving now then? What you are struggling with?

    Those telescopic constructors you could improve slightly like that:
    this(...) is referring to the overloaded constructor with the given parameters list. Get an idea... That way you save some coding and repeating same initialization lines.
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    My problem as it stands now is as I see it two fold.

    1) Whenever I run my program, a new file will be created, but no matter what I enter, [] is all that is generated.

    2) I am totally unsure as to using an ArrayList with a text file.

    My text file is as follows:


    1,"Cartagena","Spain",3
    "2015",0.2,33,26,6,"S"
    "2016",0.0,33,24,8,"SSW"
    "2017",0.0,32,25,6,"E"
    2,"Glasgow","Scotland",3
    "2015",0.0,19,8,3,"SE"
    "2016",0.1,21,11,6,"SE"
    "2017",2.1,19,11,9,"SW"



    The code for my filereader as follows:




    I thought, I have an array of strings. The file will be broken down by the split method, and that the add() method would then add the content that has been split by the split method into the repository which would then be outputted. Specifically, ID, city, country would be read from text file then written to a new file.

    So, as an experiment, I made a text file that had the following values:

    3, "glasgow" "Scotland"

    Because that matches the order of int, string, string and also matches the number of elements for the array.


    Doing so elicits the following error:
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The toString method in the model City file is as follows:

     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    When I did some debugging at the Repository




    Which would to me indicate that the add() method and the toString() method worked as expected? Hopefully this is one less thing we can cross off the list
     
    Campbell Ritchie
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:. . . Hopefully this is one less thing we can cross off the list

    No, it is one more thing to add to your list. You are going to spend ages working out why that happened. You are adding, yes, but you have a City object without an overridden toString() method. Look here about toString(). After all the work you did overriding toString(), too.



    I am not going to give you a hint that life would be a lot easier if you deleted the static nested City class.
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ok, I understand, sorry I posted here guys and sorry for clogging the forum up. I can take a hint.

     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I dont understand this assignment at all, Ive spent 3 solid days on it. I'm just cutting my losses. Thanks anyway.
     
    Campbell Ritchie
    Marshal
    Posts: 61741
    193
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:. . . I can take a hint.

    We weren't trying to give you a hint; please only see hints where they actually exist. You have however been given an assignment I don't like
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Will get back to you tomorrow, but from what I can tell now, all goes in a very chaotic way. We had City and YearData classes at hand, now other stuff appeared. Did you solve all issues you had previously, or these are related in any way?
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ok.



    https://imgur.com/a/sPJ4mYj

    The above code is the fileReader for the enclosed class diagram.

    The one thing I have observed for the above code, we create several different objects, add the contents of the text file into them, and then add each of the objects to the repository at the end, which is then outputted.

    Realising that there is striking similarity between the two, I have attempted to replicate it.

    My code is as follows:



     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Whenever I load a file or not, I get [] and Items:[] outputted.
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    So, here is the project in full.


    City

    https://pastebin.com/unNWPQFf

    YearData

    https://pastebin.com/hZ4TrHhJ

    RepositoryInterface

    https://pastebin.com/UNjdV6zq

    DAOInterface

    https://pastebin.com/KMn2njdd

    FileReader
    https://pastebin.com/iCaXFpa2

    (There are other files but they are backend/haven't touched them)
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator



    Latest form of my code.

    Outputs:


    Items: []
    Items: []

    How can I narrow down the possibilities of what is causing this please
     
    tony narloch
    Ranch Hand
    Posts: 94
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    have stress tested the program, inserting multiple output.print(repository.toString());statements within it. For example, inserting 20 of the output.print(repository.toString()); statements wwill insert into the file generated, 20 "items:[]" which would lead me to think that there is an error within the Repository class/interface, but I am for the life of me utterly unsure as to how/why this is being generated.

    I am not sure if the fact that files do not seem to be properly read is associated with this issue at present, or if rather, one error is merely masking another.
     
    Liutauras Vilda
    Marshal
    Posts: 6257
    420
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    tony narloch wrote:1) Whenever I run my program, a new file will be created, but no matter what I enter, [] is all that is generated.


    tony narloch wrote:How can I narrow down the possibilities of what is causing this please


    Hi tony once again. Try to hardcode the values to a file writing part as if they were populated automatically, so you'll see on which side of the code problem is. And report back.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!