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?
Related
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.
So for school I am making a program where we are creating a booking system where people can book a ticket for a movie that has a capacity of 10 people. People are allowed to change the time of the booking to the next day as long as the theater is not full for that day.
An array will be no good in this situation as I need to be able to remove an object from the array and make another free space in said array, and then add the removed object to a different Array for the different day. This part is suitable for an ArrayList but it has no size limit so I'm stuck with what the best solution is. Any ideas that I can look into?
Thanks
You can try the below, start from an array and convert it to list via Arrays.asList. Just note you could only use the set() method on the List, and not the add/remove methods as these would modify its size :
String[] array = {"a1","b2","c3"};
List<String> fixed = Arrays.asList(array);
fixed.set(0, "new_string"); // OK
fixed.add("aNewString"); // This will throw an exception
You can extend a class which already has the functionality you need and only override the methods required to implement new functionality (i.e. enforce a size limit).
Consider the following solution:
public class CappedList<T extends Object> extends ArrayList<T> {
private final int maxSize;
public CappedList(int maxSize) {
this.maxSize = maxSize;
}
#Override
public boolean add(T e) {
if (this.size() == this.maxSize) {
//Already reached max size, abort adding
throw new IllegalStateException("List is maxed out");
} else {
return super.add(e);
}
}
}
For completeness, you need to also override all add and addAll overloaded methods. You can then use this CappedList class instead of a simple ArrayList. A utility function isMaxedOut would be handy, in order to avoid exception handling:
public boolean isMaxedOut() {
return this.size() == this.maxSize;
}
It all depends how far you are in understanding of the language.
Let's say, first of all as a base logic that you might consider is, that you should find what is unique for 10 tickets. Obviously it's a group, which has own unique identifier and that's a date, so you have to concentrate on binding your tickets to a date groups, then you should control the amount what you are populating per date, you might need advanced control logic, rather than an usual variable that might do the job for you.
First of all, I would not store tickets in a different variables per day.
Let's go into details.
If you are obsessed by using only one specific property and that's ArrayList, I found nice answer here
But to have more precise population and access to the list later, for example to filter out specific date and see those tickets that are sold that day you should do it with a bit more structured logic, rather than a simple ArrayList(), may be you should even use different Type of variable that you should store that data in.
If you are on a bit advanced programming course, from the brief observation, for a simple task I might say that there is the way to use getter and setter methods to implement limitations and you could use any type of object to store that data, beside ArrayList.
Or you could write own functions that can control adding and removing elements from a list.
Or in more advanced way, if you have been introduced to a class concept, you could use class to define a ticket and then you could construct any logic behind it. This last one is the best way to go - to write easily readable, understandable and reusable code, or store specific data and control it the way you want.
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.
We recently switched professors and this new professor was under the impression that we had a wealth of knowledge we do not possess.
We have a programming project due and I would just like some clarification, if possible.
(From exercise 4.4) Write a method void interchange (List l) which interchanges the current element in the list and the one following it. (First make it work in the normal case; then, if you still have time, make sure it handles special cases, such as: the list is empty; the list has only one element; current is at the end of the list
(From exercise 4.6) Write a method void reverse (List l) which reversed the order of items stored in the list. Again, make sure it works for any special cases you can think of.
(From exercise 4.7) Write a method List mergeLists (List l1, List l2)which takes two sorted Lists as input, producing a new List containing all the elements of both lists, also sorted. The new list is the return value for the method.
So I created a list
ArrayList<String> numbers = new ArrayList<String>();
numbers.add("Zero");
numbers.add("One");
numbers.add("Two");
numbers.add("Three");
System.out.println (numbers);
And so I'm assuming that under this I'm to make these 3 new methods. I'm just having a hard time following his instructions. I'm not asking anyone to do my work for me, I would just like some clarification on exactly what he wants us to do, and I can subsequently attempt to do research.
Thank you in advance.
I think your professor is asking for something more abstract than what you did.
You are supposed to, first, define your own class representing a list element such as
class List {
int data;
List next;
}
Then you are given a list say List myList. It is supposed all elements are in there already.
Then you are supposed to write a function, say void reverse(List list) that, given that myList would reverse it in place etc, etc.
Exercies like this are in many books. Your professor wants to give you some abstract knowledge which is more valuable than some particular language syntax.
I have a document with 15,000 items. Each item contains 6 variables (strings and integers). I have to copy all of these into some sort of two dimensional array, what the best way to do it?
Here are my ideas so far:
Make a GIANT 2D array or array list the same way you make any other array.
Pros: Simple Cons: Messy(would create a class just for this), huge amount of code, if I make a mistake it will be imposable to find where it is, all variables would have to be string even the ints which will make my job harder down the road
Make a new class with a super that takes in all the variables I need.
Create each item as a new instance of this class.
Add all of the instances to a 2D array or array list.
Pros: Simple, less messy, easier to find a mistake, not all the variables need to be strings which makes it much easier later when I don't have to convert string to int, a little less typing for me Cons: Slower? Will instances make my array compile slower? And will they make the over all array slow when I'm searching to items in it?
These ideas don't seem all to great :( and before I start the three week, five hour a day process of adding these items I would like to find the best way so I won't have to do it again... Suggestions on my current ideas or any new ideas?
Data example:
0: 100, west, sports, 10.89, MA, united
*not actual data
Your second options seems to be good. You can create a class containing all the items and create an array of that class.
You may use the following:
1. Read the document using buffered reader, so that memory issues will not occur.
2. Create a class containing your items.
3. Create a List of type you need and store the elements into it.
Let me know in case you face further problems.
If you already have the document with the 15000 * 6 items, in my experience you would be better served writing a program to use regex and parse it and have the output be the contents of the java array in the format you want. With such a parsing program in place, it will then also be very easy for you to change the format of the 15000 lines if you want to generate it differently.
As to the final format, I would have an ArrayList of your bean. By you text thus far, you don't necessarily need a super that takes in the variables, unless you need to have subtypes that are differentiated.
You'll probably run out of static space in a single class. So what I do is break up a big class like that into a file with a bunch of inner nested classes that each have a 64K (or less) part of the data as static final arrays, and then I merge them together in the main class in that file.
I have this in a class of many names to fix:
class FixName{
static String[][] testStrings;
static int add(String[][] aTestStrings, int lastIndex){
for(int i=0; i<aTestStrings.length; ++i) {
testStrings[++lastIndex]=aTestStrings[i];
}
return lastIndex;
}
static {
testStrings = new String[
FixName1.testStrings.length
+FixName2.testStrings.length
+FixName3.testStrings.length
+FixName4.testStrings.length
/**/ ][];
int lastIndex=-1;
lastIndex=add(FixName1.testStrings,lastIndex);
lastIndex=add(FixName2.testStrings,lastIndex);
lastIndex=add(FixName3.testStrings,lastIndex);
lastIndex=add(FixName4.testStrings,lastIndex);
/**/ }
}
class FixName1 {
static String[][] testStrings = {
{"key1","name1","other1"},
{"key2","name2","other2"},
//...
{"keyN","nameN","otherN"}
};
}
Create a wrapper (Item) if you have not already(as your question does not state it clearly).
If the size of the elements is fixed ie 1500 use array other wise use LinkedList(write your own linked list or use Collection).
If there are others operations that you need to support on this collection of items, may be further inserts, search( in particular) use balanced binary search tree.
With the understanding of the question i would say linked list is better option.
If the items have a unique property (name or id or row number or any other unique identifier) I recommend using a HashMap with a wrapper around the item. If you are going to do any kind of lookup on your data (find item with id x and do operation y) this is the fastest option and is also very clean, it just requires a wrapper and you can use a datastructure that is already implemented.
If you are not doing any lookups and need to process the items en masse in no specific order I would recommend an ArrayList, it is very optimized as it is the most commonly used collection in java. You would still need the wrapper to keep things clean and a list is far cleaner than an array at almost no extra cost.
Little point in making your own collection as your needs are not extremely specific, just use one that is already implemented and never worry about your code breaking, if it does it is oracles fault ;)