How do you call a method from another class? - java

I'm trying to write a code for a method which has certain conditions which needs to be met. I believe that I need to use methods from a different class to meet the conditions. I've done the last 2 conditions but I have got no clue on how to go about the others because I do need to access methods from a different class.

It seems like using the shtlCode, you can obtain the proper Shuttle instance from your shuttleMap, like so:
public boolean canTravel(int pCardId, String shtlCode)
{
Shuttle shuttle = shuttleMap.get(shtlCode);
...
Once you have the Shuttle, you can then find the Asteroid it's currently on:
Asteroid currentShuttleAsteroid = shuttle.getSourceAsteroid();
Having these two objects, it's up to you to ensure the conditions have been properly met. (And also, to ensure that your shuttleMap contains a Shuttle with the code specified, etc.)

As Craig suggested above, keep the Shuttle that you fetched from the hashmap. You will need it to implement most of the remaining checks.
canTravel is given a card id, but is going to need the PearlCard itself. But where to get it from? Three possibilities:
The caller can pass a PearlCard into canTravel instead of the integer ID, if it has it.
canTravel could search for a PearlCard with the matching ID in the source asteroid's list of PearlCards. (And if it's not in there, then you can't travel anyway.)
Or you may want to add a HashList of all PearlCards to your program, similar to shuttleMap.
Then get the shuttle's destination asteroid and see if has room for one more PearlCard (compare PearlCard list's length to the asteroid's capacity). Also check to see if the card has enough credit and rating for that asteroid. (You didn't show PearlCard class so I don't know the exact code, but I'm guessing you'll have no trouble with that part.)
Note: your current code seems to have at least one bug. canTravel searches the asteroid list for the card ID. Like I said above you will need to get the card from somewhere, but it's not going to be in asteroidList.

Related

How can I use a Linked list with my Handler class in Java?

I am making a simple game which has an array of objects called beats which move along the screen towards a stationary player like a basic rhythm game, and I have decided that using a linked list is the best way to track the nearest beat to the player
Currently I am trying to add to the linked list, and have this as a starting point:
public static LinkedList<Beat> beatLinkedList = new LinkedList<Beat>();
The linked list is public and static as it needs to be accessed in a different class.
int startingPoint = 800;
//For loop 51 times
for(int i=0;i<=50;i++){
//modifier to start position to create differing gaps between beats
int startModifier = random.nextInt(50);
beatLinkedList.add(new Beat(startingPoint,300,ID.Beat));
System.out.println(beatLinkedList.get(0));
//redefines the starting point for each beat
startingPoint = startingPoint+50+startModifier;
}
}
When I want to render the objects however I need to use the handler class, to add the objects to a linked list of gameobjects which has the render method called on them which I would like to keep the same ideally meaning I need to use the handler classes addObject method:
public void addObject(GameObject object){
//linked list built in method to add an object
this.object.add(object);
}
For using an array this solution worked
But something similar for the linked list does not
handler.addObject(beatLinkedList.add(new Beat(startingPoint,300,ID.Beat)));
I should also add that when I get the element at position 0 it outputs all 51 objects which is also a problem.
With trying to use the handler like this I am given an exception saying "addoObject in Handler cannot be applied to boolean"on line 50:
handler.addObject(beatLinkedList.add(new Beat(startingPoint,300,ID.Beat)));
I'm not sure about this but it seems that I need to give a pointer to a location when using the add method and so I tried this:
beatLinkedList.addLast(new Beat(startingPoint,300,ID.Beat));
And this method still has the problem of adding all 51 objects to the same point in the list, which I imagine is something to do with being in a for loop still.
handler.addObject(beatLinkedList.addLast(new Beat(startingPoint,300,ID.Beat)));
Trying to utilise this with my handler class results in a different error from before saying that the 'void' type is not allowed as a parameter. I'm really not sure where to go from here.
beatLinkedList.addLast(new Beat(startingPoint,300,ID.Beat));
handler.addObject(beatLinkedList.getLast());
Solved thanks to Abra's comment, I decided to add the object to 2 seperate linked lists, one of just the beats, and one containing all the game objects, which allows them to be rendered properly, while also allowing beats to be identified and removed when necessary.

Java: Wrapping objects in some type of collection to store duplicates in a set

I want to make a set of some type of collection (not sure which one yet) as a way of "storing duplicates" in a set. For example if I wanted to add the integer 5 with 39 additional copies I could put it into an arraylist at index 39. Thus if I were to get the size of the arraylist, I would know how many copies of 5 existed within the set.
There are a few other ways I could implement this but I have yet to decide on one. The main issue I'm having with implementing this is that I'm not sure how I can "dynamically" make arraylists (or whatever collection I may end up using) so that whenever someone were to call mySet.add(object), the object is first inserted into a unique arraylist then into the set itself.
Can anyone give me some ideas on how I could approach this?
EDIT:
Sorry I should have been more clear in my question. The point of the code that I'm writing is that we have a set-like collection that allows duplicates. And yes some of the associated methods will be re-written/will have to be re-written. Also my code should be written under the assumption that we do not know what type of object is being inserted(only one data type per set though) nor how many instances of the same object will be added nor how many different unique objects will be added.
I would rather go for using a Map like
HashMap list <Object, Integer>
where Object is the Object that you want to count and Integer is the count
You could try guava's MultiSet, I think it's what you want.
It can store the count of each object. What you need to do is just
multiSet.put(object);
And if it is put for the first time, like you said, a new list will be created, or its count will added by one.

Creating a storage class, sorted and limited by weight

Sorry for asking this, but i could really use a new PoV. Been sitting on it for days and can't wrap my head around it.
Basically, i have a Class Screw, whose object has attributes like length, material etc. It also saves the amount of screws and the weight this amount has.
So basically it sets Screw1 = 1cm, Steel, 200 Screws, 10kg (not like that of course, but for simplicities sake)
Those Screw objects are to be saved in a storage unit, sorted. So every combination of attributes gets it's own space to be saved in. It is limited by weight, so if you add 25kg of screws, you'd need two storage spaces, creating a new box to store them in.
It shall also be possible to take out screws, removing a storage space, if the weight of a box would drop below 0 and removing the remaining amount of screws from the new box.
public class Schraube {
private int schraubenArt,Material,SchraubenAnzahl, Entnahmeprotokoll;
private double durchmesser,laenge, gangHoehe,gaengigkeit,gewicht;
// lots of constructors and methods for calculations
}
I also had a storage class that would loop through all the possible combinations of Schraube and would then .add() them to an ArrayList, giving it maximum weight.
Now, how would you go about doing this? How do you add Stoagespaces if you go over weight 20kg? How would one do this efficiently without creating huge arrays of 561 spaces times 7?
I hope it's kinda clear what i am trying to do. Head hurts and i can't figure it out anymore.
My advise would be not to create a storage class since the Schraube class does not represent a singular entity but the properties of multiple entities. In this case you are setting the number of screws in a class that represents a screw. There are two solutions to this problem.
Create a getter method that calculates the number of storage spaces.
public int getNumberOfStorageSpaces(){
.... // Calculation logic
return numberOfStorageSpaces;
}
Or you can separate the type entity from quantity. In this case you would remove the SchraubenAnzahl property from the Schraube class, create another entity that encapsulates the type and quantity of screws called Schrauben. Then you would need a StorageSpace entity that represents a space and the quantity it can hold. Finally you would need an entity that represents the relationship between screws and storage spaces. This would be a more complex solution. To better understand the issue I recommend using an Entity Relationship Diagram to better illustrate the relationship between your entities.

Why do i separate List and Node class?

Let me ask this question taking Java code mentioned in the query link.
In the same query link, a supplementary answer says: "In general, we need to separate List and Node classes, your List should have an head and your Node will have item and next pointer."
In addition, my class lecture says, there are two reasons for separating List and Node class.
Reason 1:
Assume user X and user Y are pointing to the first List_Node in that list
After adding soap item by user X in the shopping list, below is the situation,
So, User Y is inconsistent with this situation.
Reason 2:
Handling empty list.
user X pointing to an empty list, that mean X is null.
X.nth(1); //Null pointer exception
My question:
Reason_1 could have been handled by inserting new node after last node. Reason_2 could have been handled, as part of error check in the code.
So, Why exactly we need to separate Node and List class?
Note: Java code has item of type intinstead of type Object that can accommodate strings. I did not want to change this code again.
Reason_1 could have been handled by inserting new node after last node.
But that is changing the problem. Lists are ordered. Adding an element before an existing element or after an existing element are different operations. The data structure must be able to handle both operations, otherwise it is not a proper list.
Reason_2 could have been handled, as part of error check in the code.
That wouldn't work. The code of your list abstraction can't handle the NPE. If you attempt to call x.nth(1) and x is null, the exception is thrown before you get into any of the code that implements the list. Therefore, the (hypothetical) error handling in the list code cannot be executed. (Java exception handling doesn't work like that ...)
And as you correctly point out in your comment, forcing code that uses a list to handle empty lists as a special case would be bad list API design.
In short, both of the reasons stated are valid. (IMO)
Here are some very good reasons:
Separate implementation from interface. Perhaps in the future someone will find a new perfectly good implementation of your life involving a row of carrier pigeons moving elements around. Should your client code have to update everything with methods flapWings and rewardPigeon instead of manipulating nodes? No! (More realistically, Java offers ArrayList and LinkedList IIRC).
It makes more sense. list.reverse() makes sense. node.reverse()... what? Does this change every other node recursively or not?
Speaking of that reverse method, if you implement it right now you can implement it in O(N). You know if you have an int orientation; that is 1 or -1, you can implement it in O(1)? But all subsequent operations need to use that bit, so it's a meta-node operation, not a node operation.
Empty lists are possible. Empty nodes don't make sense. This is your (2). Imagine this: I am a client of your software. You have list == node. A rival vendor offers separation. You say "oh it works fine just add an error check in your code." Your rival does not. Who do I buy from? This is a thought experiment meant to convince you these really are different, and the former does have a defect.

Choose a class depending on the class' attribute

I want to write a method in java that will select certain words based on an input.
For example, if the choices were a dog, cat, lizard, eagle
and someone types in wings, it'll check to see if the choices have that attribute.
I don't know how complex this is but we've learned for loops, return, if, else and scanners so far.
You can probably maintain a list of attributes for each object, then check if the user typed attribute is part of the list for all object types you have in hand.
I suggest you look at the ArrayList JavaDoc, you will need to use it to maintain the list of attributes. If you don't feel at ease with using an ArrayList object to hold onto your attributes, you may want to use a String array instead, which will work fine too. You will also need to defined a class hierarchy and define a method that will be available in all subclasses (here's a tutorial on inheritance).
Edit
I posted this first answer before reading the comments.
If your only assignment is to provide a list of components that freeze at the user specified temperature, then a list of attributes isn't necessary. You can define a super class (lets say Element) that will define an abstract method public int getFreezingTemperature (). Then, in all subclasses, you will have to implement this method. As an example, if you create a class Water:
public class Water extends Element {
#Override
public int getFreezingTemperature () {
return 0;
}
}
And repeat the same for every element you have to create. Once you are done, whenever a user inputs a temperature, you can query your elements via the method getFreezingTemperature (), and whenever the returned temperature is above the user specified temperature, add it to a list of elements that freeze at the specified temperature.
I'm attempting to answer the substance-temperature question you mentioned in your comment. You could make an arrays as such:
String[] substances = new String[number of substances given];
Then place the substances into the array in the same order that they are given in the assignment. You can then check the user's input and determine at which index the name of the substance corresponding with their input is. For example:
//code to initialize array of substances goes here, call it "substArray"
//code to make scanner goes here, call it "scan"
int temp = scan.nextInt();
if(temp == -100)
{
System.out.println(substArray[index of substance corresponding with -100]);
}
else if...
...
This seems to be a very messy and a not very elegant program to write without use of separate classes, but hopefully this is within the range of your current knowledge and understanding.
I hope this helps,
Tyler
Edit: after reading your comments, it looks like you're going to want to do something like this.
//create your scanner, using whatever resource you are told to use
int temp=scanner.readInt()
//read in the given temperatures
if(substance1freezingpoint > temp){
System.out.println("substances 1 will freeze at " + temp);
}
if(substance2freezingpoint > temp){
System.out.println("substance 2 will freeze at " + temp);
}
....
A couple of things to note about that implementation.
It assumes that more than one substance can freeze at temp. If that isn't the case, you're going to want to use else ifs. As a question to test your learning: why is that?
It doesn't store which substances will freeze at a certain temperature, it just prints them out to the screen. How would you modify this to store the substances which meet the criteria
It doesn't deal with boiling points, but it's a pretty easy modification to make it do that.
So, does that code at least get you off on the right foot, or does it not satisfy what the problem is asking?

Categories