Full access to class's elements , which contain into other class - java

I think it's normal desire to have access for manipulating with data. Should i create getters/setters in Record class, if i already use Storage for this goal, made on Record? Or what need to do?
public class Storage {
List<Record> record;
public Storage(){
this.record = new ArrayList<Record>();
}
public void addRecord(Record record) {
this.record.add(record);
}
public Record getRecord(int number){
return this.record.get(number);
}
public class Record {
private int number;
private int count;
private Object code;
/* public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
} */
public Record(int number, int count, Object code) {
this.number = number;
this.count = count;
this.code = code;
}
#Override
public String toString() {
return (this.number+" "+this.code+" "+ this.count);
}
}

According to me it is not require to write setter and getter methods until you don't want to modify them.In your code you have initialized fields in constructor and overridden toString() method to get meaningful content of Record object and never trying to modify Record 's fields directly.
I strongly feel that it is not required.

Related

Why do I keep getting a Null Exception Error?

I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin can hold upto a maximum of 3 passengers. I'm trying to set passenger details but i keep getting this error
Cannot invoke "classes.Passenger.setFirstName(String)" because
"classes.Main.myShip[0].passenger[0]" is null at
classes.Main.main(Main.java:22)
Ship.java
public class Ship
{
public static Scanner scanner = new Scanner(System.in);
public static Cabin[] myShip = new Cabin[12];
public static void main(String[] args)
{
for (int count = 0; count < 12; count++)
{
myShip[count] = new Cabin();
}
myShip[0].passenger[0].setFirstName("a");
}
}
Cabin.java
public class Cabin
{
int cabinNumber;
Passenger[] passenger = new Passenger[3];
public Cabin()
{
}
public Cabin(int cabinNumber, Passenger[] passenger)
{
this.cabinNumber = cabinNumber;
this.passenger = passenger;
}
public void setCabinNumber(int cNumber)
{
cabinNumber = cNumber;
}
public int getCabinNumber()
{
return cabinNumber;
}
}
Passenger.java
public class Passenger
{
String firstName;
String lastName;
int expenses;
public Passenger()
{
}
//Constructors
public Passenger(String cabinFirstName, String cabinLastName, int pExpenses)
{
firstName = cabinFirstName;
lastName = cabinLastName;
expenses = pExpenses;
}
public void setFirstName(String cabinFirstName)
{
firstName = cabinFirstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String cabinLastName)
{
lastName = cabinLastName;
}
public String getLastName()
{
return lastName;
}
public void setExpenses(int pExpenses)
{
expenses = pExpenses;
}
public int getExpenses()
{
return expenses;
}
}
Please be kind enough to help me out.
Your model is wrong. A ship can (and does) have cabins with no occupants. You have provided no way to have unoccupied cabins. Your cabins need to be fully booked before the ship can be built!
I would consider redefining your Cabin class to be constructed empty -- which means it would have a constructor with a signature like Cabin(), and then provide a way to assign Passengers to Cabins. Maybe this would be a method in the Cabin class, like
boolean assignPassenger(Passenger p) {
... check occupancy...
... return false if full up ...
... otherwise add 'p' to the passenger array ...
... and return true ...
}
You're halfway there in that you're attempting to set the Cabins in the Ship by using a Cabin() constructor -- which is essentially an empty Cabin -- but you have not actually implemented a constructor with that signature.
What I'm getting at here is that, rather than just tweaking some Java, I think you should rethink it a bit. You'd want, I think, to be able to have unoccupied cabins and to be able to determine which cabins are occupied.

Java, how to sort an list of Nodes by an objects field

I made an class called myLinkedList that stores nodes from a class called LinkNodes that takes an object with an name(String), as a field. I want to sort the nodes in my list alphabetical, from the memberPlayer field firstName
public class LinkNode {
public memberPlayer player;
public LinkNode next;
public LinkNode() {
this(null, null);
}
public LinkNode(memberPlayer player) {
this(player,null);
}
public LinkNode(memberPlayer player, LinkNode next) {
this.player = player;
this.next = next;
}
public String toString() {
String result = player + " ";
if (next != null) {
result += next.toString();
}
return result;
}
}
I have tried with the collection.sort method but, without luck, as i tried to use it on an list that i created myself, but it worked fine, when i just used the objects. Is there somehow special i need to do, if I want to acces the field of an object inside a node?
memberPlayer class:
public class memberPlayer implements Comparable<memberPlayer>{
private String firstName;
private String lastName;
private int age;
private String team;
}
You should implement the compareTo method in the Comparable interface to use a specific field.
#Override
public int compareTo(Object o) {
MemberPlayer player = (MemberPlayer)o;
return this.firstName.compareTo(player.firstName);
}
P:S Always use proper conventions when naming classes.

Can't print objects stored in HashMap?

I'm working on an assignment for my java class, and we just started learning about HashMaps and we have this assignment where we create enumerated data and store it in a hashmap to print out later. What I can seem to figure out is to be able to print the elements of the HashMap. Here is my project so far:
public class Driver <enumeration>
{
private static HashMap<String, State> stateList = new HashMap<String, State>();
public static void main(String args[]) throws IOException
{
stateList.put("1", State.CA);
stateList.put("2", State.FL);
stateList.put("3", State.ME);
stateList.put("4", State.OK);
stateList.put("5", State.TX);
for(State value : stateList.values())
{
System.out.println(value);
}
}
}
public enum State
{
CA(new StateInfo("Sacramento", 38802500)), FL(new StateInfo("Tallahassee", 19893297)),
ME(new StateInfo("Augusta", 1330089)), OK(new StateInfo("Oklahoma City", 3878051)),
TX(new StateInfo(" Austin", 26956958));
private StateInfo info;
private State(StateInfo info)
{
this.info = info;
}
public StateInfo getInfo()
{
return info;
}
public String toString()
{
return "";
}
}
public class StateInfo
{
private String capital;
private int population;
public StateInfo(String capital, int population)
{
this.capital = capital;
this.population = population;
}
public String getCapital()
{
return capital.toString();
}
public int getPopulation()
{
return population;
}
public String toString()
{
return "";
}
}
Now when I try to run the program, it just terminates without even as much as a reference number for the state objects I'm trying to print. What I think is wrong is in the StateInfo class so I tried changing some things but to no prevail. Can anyone tell me if my suspensions are correct, or am I overlooking something?
You have overridden the toString() method in the State class:
public String toString()
{
return "";
}
Therefore you get no output at all as for every value the toString() method is called in your loop:
for(State value : stateList.values())
{
System.out.println(value);
}
To be more precise: You should get 5 empty lines.
Remove the toString()method in order to use Java's default toString() implementation which returns the classname+hashCode() or make it return e.g. "Capital: " + info.getCapital().

ArrayList - Remove the first added object and no repeats

I'm doing an assignment where I have to add a Present to an ArrayList of presents. There can be a maximum of 10 presents in the ArrayList and the present is defined by its type, cost and name, and if these three fields are the same, then it's the same present and it cannot be added to the ArrayList.
When an eleventh present is added, the first present added to the list has to be removed and this new present take its place.
And I'm really stuck.
This is my code so far:
public class GiftList
{
private ArrayList<Present> presents;
public GiftList() {
presents = new ArrayList<Present>();
}
public void addPresent(Present present) {
if (presents.size() <= 10) {
presents.add(present);
}
else {
//**Remove oldest present in list, then
presents.add(present);
}
//**Another if statement for no duplicated presents
}
public class Present
{
private String name;
private String type;
private double cost;
public Present(String name, String type, double cost) {
this.name = name;
this.type = type;
this.cost = cost;
}
}
Hints:
Look on how to implement equals() and hashCode() for Present.
Check: List.remove(int index) and List.contains(Object).
If you add an equals method to your Present object:
public class Present {
private double cost;
private String name;
private String type;
public Present(String name, String type, double cost) {
this.name = name;
this.type = type;
this.cost = cost;
}
public boolean equals(Object o) {
if (o instanceof Present) {
Present p2 = (Present) o;
return name.equals(p2.name) && type.equals(p2.type) && Double.valueOf(cost).equals(p2.cost);
}
return false;
}
public int hashCode() {
return Objects.hash(name, type, cost);
}
}
Then the following code could be used:
List<Present> myList = new ArrayList<Present>() {
#Override
public boolean add(final Present present) {
if (contains(present)) {
return false;
}
if (size() >= 10) {
remove(0);
}
return super.add(present);
}
};
myList.add(new Present("name", "type", 1.0));
For more info, see Object.equals and List.remove.
However, I believe the best way to do this would be to either use a Set which automatically handles the no repeats-problem or some kind of Queue. If some kind of hash-solution is used (e.g. a HashSet) don't forget to implement the hashCode function (more info on hashCode here).
Edit: added the hashCode-implementation after input from # TJamesBoone.
you can just remove the first element by calling
presents.remove(0);
check this
http://www.tutorialspoint.com/java/util/arraylist_remove.htm
For duplication it would be better if you used a Set
But, if you stick with ArrayList, then implement equals/hashcode as already mentioned and now there are
two options:
Either always call remove (for the new object) before adding it, so it always removes oldest entries
or check existence before adding.
Although 2nd option might be more efficient it depends on how you want to utilize your queue (how FIFO is defined for duplicated objects?). If a new object already exists in the list, do you want to update its index, as it was a new entry? if yes you update its status and it will be deleted at a later time than keeping the older one.
Looking at your description I think this could do your job
int rotatingIndex =- 1 ; //variable maintaining current value of the index.-1 when no elements are present
public void addPresent(Present present) {
rotatingIndex = (rotatingIndex + 1)%10;
presents.add(rotatingIndex,present);
}
I would suggest to override equals for Present, and use linkedlist as queue. like;
public class Present
{
private String name;
private String type;
private Double cost;
public Present(String name, String type, Double cost) {
this.name = name;
this.type = type;
this.cost = cost;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
#Override
public boolean equals(Object obj){
if(obj == null || !(obj instanceof Present)){
return false;
}
Present anotherPresent = (Present) obj;
if(this.getName() == anotherPresent.getName()
&& this.getCost() == anotherPresent.getCost()
&& this.getType() == anotherPresent.getType()){
return true;
}
return false;
}
}
Gift class:
public class GiftList
{
private LinkedList<Present> presents = new LinkedList() ;
public void addPresent(Present present) {
if (presents.contains(present)){
// do nothing it already exists!!
return ;
}
if(presents.size() <= 10) {
presents.add(present);
}
else {
presents.pop();
//**Remove oldest present in list, then
presents.add(present);
}
//**Another if statement for no duplicated presents
}
}

NullPointerException when i call a constructor with arguments

firstly, really sorry for my poor english.
i am trying to make a list of movies.
in main class i call the insert() method and in it i make an object of MovieListNode class in order to do what is needed.
class main{...
while( FileParsers.hasNextMovie() ){
MovieData movie = FileParsers.getNextMovie();
System.out.println( movie );
/* fill the movie lists here */
UnsortedMovieList vag=new UnsortedMovieList();
vag.insert(movie);
}
the insert method of unsortedmovielist:
class UnsortedMovieList{...
public void insert(MovieData data){
MovieListNode node=new MovieListNode(data.getId(),data.getTitle(),data.getYear(),data.getRating(),data.getVotes(),data.getDuration(),data.getGenres());
if(isEmpty()){
tail=node;
}else{
head.setPrevious(node);
}
node.setNext(head);
head=node;
size++;
}
and the MovieListNode class(sorry for the size):
public class MovieListNode {
private int id;
private String title;
private int year;
private double rating;
private int votes;
private int duration;
private ArrayList<genre_t> genres;
private int i=0;
private MovieListNode previous;
private MovieListNode next;
public MovieListNode(){}
public MovieListNode(int id, String title, int year, double rating, int votes, int duration, ArrayList<genre_t> genres) {
this.id=id;
this.title=title;
this.year=year;
this.rating=rating;
this.votes=votes;
this.duration=duration;
this.genres=genres;
}
public int getId() {return id;}
public String getTitle() {return title;}
public int getYear() {return year;}
public double getRating() {return rating;}
public int getVotes() {return votes;}
public int getDuration() {return duration;}
public ArrayList<genre_t> getGenres() {return genres;}
public MovieListNode getPrevious() {return previous;}
public MovieListNode getNext() {return next;}
public void setNext(MovieListNode next) {this.next=next;}
public void setPrevious(MovieListNode previous) {this.previous=previous;}
}
when i do this i get NullPointerException in line MovieListNode node=new MovieListNode(data.getId(),data.getTitle(),data.getYear(),data.getRating(),data.getVotes(),data.getDuration(),data.getGenres()).instead if i write 'MovielistNode node=new MovielistNode();' i dont get any errors but it's not what i want.
if anyone could help i would be grateful. thanks. (if u want more information about something in my code please let me know)
One or all of the fields in your MovieData object are null. You need to investigate your method:
FileParsers.getNextMovie();
You use this method to initialize an object of type MovieData If this method does not declare and initialize a MoveData object with a constructor that initializes all of the data fields, and then return that object, you will get a NullPointer when you try to call one of the getters
It is probably genres since the other fields have default initializations.
UPDATE:
In your Fileparsers class. I notice the code in the getNextMovie() method:
if( dataLine==null || genresLine==null )
return null;
}
It may be that your logic to readLine() is not being used correctly. So I suspect you may be ending up with null lines and therefore returning a null MovieData object. You should check if the next line is null before assigning it.

Categories

Resources