Writing code with multiple Class Methods and String Arrays - java

So what I am trying to do is create a code that lists music artists names using user input.
It has to have multiple classes so I will have a main class, and a class for each decade of music.
Music.java
six.java
seven.java
eight.java
In these classes I need to create string arrays that contain artist names, and be able to generate the entire list once prompted.
To give a better idea of how the code will run it would go something like:
Choose a decade of music:
70's
Choose a genre of music:
Rock
Choices are: Rolling Stones, Talking Heads, etc.
That's all I need it to do but I'm getting stuck on what to put in the main class "music.java" to get it to read the other classes and furthermore how to write the decade classes.
I understand I don't have much to offer you guys here but any help would be appreciated.

In general terms, you need a class in this rough form:
public class Artist
{
public int decade
public string genre
}
Then some code to use it:
... code to retrieve some kind of collection (e.g. an array or list), of artists as Artist objects (you'll need to do this by retrieving the artist data from a database)
... code to iterate through the collection to do what you want with it:

I would only have a class named Band and a container class for all bands named BandRegister. The Band would hold a Set of values representing the decade, which are added using associateWithDecate(int decade) method:
Class BandRegister:
Map<Integer, Set<Band>) decadeMap = new HahMap...
public addBand(band);
{
//define logic for adding the decade and band to decadeMap
}
Class Band:
Set<Integer> decades = ...
public associateWithDecate(int decade)
{
//add decade to decades if not already included
}
In Main:
BandRegister breg = new BandRegister();
Band stones = new Band("Rolling Stones");
stones.associateWithDecate(60);
stones.associateWithDecate(70);
stones.associateWithDecate(70);
stones.associateWithDecate(90);
stones.associateWithDecate(0);
stones.associateWithDecate(10);
breg.addband(stones);
That way, you can get a listing of decades for each band and also in the register you can get a listing of bands for each decade

Related

How to organize classes and Lists for Java text adventure

I am creating a Java text adventure and am trying to make it as object-oriented as possible. I'm debating how to handle the Rooms and the available items in that room. Currently I have the room class set up like this:
String name;
String description;
List<Item> avaliableItems;
List<Item> inspectableItems;
Room(String name, String description, List<Item> avaliableItems, List<Item> inspectableItems,) {
this.name = name;
this.description = description;
this.avaliableItems = avaliableItems;
this.inspectableItems = inspectableItems;
}
I have a Game class which I planned on initializing the Rooms and I also have an Input class which checks the user input and performs actions. My problem is I don't know what to do with the Item lists. I don't want to have to create a new Room and multiple new Lists for each room. I feel like this would get messy very quickly. Is there a way to get this same idea across in a cleaner way? Each room having its own class would be overboard I think. Thanks.
At the end of the day level creation is going to involve a bunch of hardcoded info. That can be messy if it is done wrong. One approach that has worked well for me is to serialize the rooms with their initial items into a text file, and then make one class which handles initializing all rooms based on the text file. That way you don't have lines upon lines of hardcoded item data in your code, and all of the level setup info is in one place.

Java new ArrayList of Object myList

i have an ArrayList called e.g. Fridge
List<Food> fridge = new ArrayList<Food>();
An simple explanation:
Because i want to keep my fridge organized i want to put my food into seperate drawers.
I already have the Classes Meat, Fruit and Bread.
The point i am struggling with is to create new ArrayList's which picture the different drawers.
My goal is to have the fridge List a parent list and meat,fruit,bread as children of this list.
fridge (Parent)
---meat (Child)
---fruit (Child)
---bread (Child)
Do you have any ideas how to realize this ?
I'm glad for any help
EDIT:
The Objects i want to add to thesublists contain informations such as String obj.name; double obj.weight; double obj.price; i want to add the objects to the sublists and be able to read the sublists out again.
"fridge" shouldn't be a simple ArrayList since it needs to have its own more complex state and behaviors. Instead it should be a full fledged class and should contain 3 (or more) ArrayLists: meatList, fruitList, and breadList, as well as methods to put items in each of the lists, as well as methods of retrieving items, and methods for printing or displaying items.
Likewise Food can have subclasses for Meat, Fruit and Bread (although per Good Housekeeping, one shouldn't put bread in a refrigerator -- it causes condensation and sogginess).
I don´t get 100%ly what you want but I guess you just want to store your Food data.
1.)
Just make an List of Lists:
ArrayList<ArrayList<Food>> fridge;
where every inner List presents an drawer. Meat, Fruit, etc. will be an Subclass of Food.
2.)
make a Map with an key as the "name" of the drawer
HashMap<String, ArrayList<Food>> fridge;
With that you can easily get the "drawers" content. However that doesn´t change much to the above.
3.)
Make an Fridge class which stores all your stuff. And since an Fridge can hold more than just Food make an interface which defines what properties an Thing has which can be stored.
interface Storable{
String getName(); int getId(); String getType(); void use();
}....//whatever everything which will be stored has.
class Fridge{
HashMap<String, ArrayList<Storable>> contents;
void add(Storable food){
this.contents.put(food.getType, food); //or instead of #getType use the class of the food.
}
and then your Food, Meat, etc:
class Food implements Storable{
//implement the inherited Methods
}
Then you have again some choices, like make for each type an class (Meat, Bread, etc) or just make in Food an field "type" which describes what it is. It highly depends on your "mental model".
You are getting your "mental" model wrong. A fridge is much more than just a List that contains other lists.
Just imagine the "real fridge" in your kitchen. There is much more to it than just some lists (sorted by content)!
Thus you should first try to figure for yourself what the purpose of a "fridge" within your mental model is. Which behavior (interface) should it offer to users of that class?!
Example: is it really relevant that a fridge knows its content by "type"? Or would it matter more how entries in that fridge are physically ordered?
So besides the excellent answer from Hovercraft you might want to step back even further in order to really define what the terms you are using should mean within your program!

Create a country with specific values from a pre-determined list

Background
I'm currently working on an Android application which asks the user a question. At the moment I'm creating the modules for asking the questions. Right now I'm working on a topography module, which will be able to ask the user all kinds of questions about a certain country that will be shown to them.
Problem
For this module I will need a list of all the countries in the world. I currently have a Country class that has a String[] array that has all the countries English names in it (±200). I also want a few other properties in the Country class, such as their capitals, provinces and the translations for them. All of these properties should be selected from a predetermined list. This list should also be rather flexible, so that it in the future I can easily add new properties to them.
The problem I'm currently having is that I'm not quite sure how to create such a list. I've had a couple of ideas but all of them seem faulty, cumbersome or they just plain don't work in Java. Here is an example of a few of my ideas:
Create a multidimensional array that holds all the countries values which can then be easily selected with predefined indices. This is something that I often use when programming in PHP, because it can hold all kinds of different types. You can also define the keys (indices) of the array in PHP, but this doesn't work in Java.
Create an enum for all the countries and use the int associated with the specific country to select values from a capital/province array. This is a bit too cumbersome for my liking, it would require me to create an enormous array everytime I would want to add another property/question for the country (making a mess of the Country class in my opinion).
Create classes for all the properties I want Country to have. This has the advantage that I could expand on these classes further with more information (such as giving a Capital class properties such as: amount_of_residents), and has the advantage of perhaps creating a sophisticated translation class. I'm just wondering if this is the most efficient/logical way to proceed?
I feel that there should be some very nice solution for this problem I'm facing, but for the love of me I just can't figure it out. If you guys have any idea as what would be the best option (I'm currently leaning to option 3), or give me another solution to the problem that's more efficient, it would be greatly appreciated.
Note: I haven't added any code, because I didn't feel it would be necessary. If anyone would like to see some code I would be happy to provide it.
I believe you should go with the last approach, it should be something like the below sample code P.S
class Country {
String countryName;
String capital;
int noOfResidents;
List<String> provinces;
//getter & setters for them
public void setCountryName(String countryName)
{
this.countryName=countryName;
}
//And so on & forth
}
class SetCountryDetails {
public static void main(String[] args){
Map<String, Country> countryData = new HashMap<String, Country>();
//Using a map facilitates easier fetch for the countries. You can just
//provide the key of the country, for an instance to fetch the data for Germany
//just write countryData.get("Germany");
Country countryOne = new Country();
countryOne.setCountryName("Germany");
countryData.put("Germany", countryOne);
Country countryTwo = new Country();
countryOne.setCountryName("India");
countryData.put("India", countryTwo);
}
}
This approach enables you to add or delete a property to the Country class anytime without much hassle.
I'm not sure I totally understand what the issue really is. Basically you seem to have a domain object called Country that has a number of properties, and you seem to want to extend dynamically? Perhaps some code would help to solve your problem.
As per my understanding from your question, You need to use the list of Countries and respective properties of those Countries. And those properties need to be flexible in future to add/remove. For this you can maintain the list of countries and related properties in a property file or an XML file, which can be flexible in future to add/remove properties if required. If my understanding is wrong then make it clear for me. :)

Organizing workout info with hashmaps and arrays

I'm looking to create a java program that will store a workout with each lift and reps performed. But I'm not exactly sure how to organize the data structure. I was thinking to use a hashmap to store everything with the hashcode being the date performed. So something performed december 24, 2013 would be stored at 122413. The element I would want to store there would be like an array of arrays, with each array displaying the lift and each following element would alternate between the reps performed and weight. Here's a visual example of that.
arr = [["bench press",10,185,9,195,8,205],["shoulder press",10,95,8,95,6,95],...]
So if I wanted the reps and weight performed for my second set of bench press it would output like:
You performed arr[0][1] reps of arr[0][2] for arr[0][0]
---
You performed 10 reps of 185 for bench press
-----
I know this can be done in python, but I'm not sure that it's available in java?
I'm having issues implementing as from what I've found the datatypes of an array all need to be the same type (no string AND int), which is actually okay because these numbers don't really have a numerical value and will just be displayed. But I'm also a little stuck on getting an array stored in a hashmap and building an array of arrays.
So, my question: is this a doable implementation for what I'm trying to accomplish? Or is there a better way to go about organizing this? I'd like to keep the data organized by date as I showed earlier if possible. Any help or suggestions would be wonderful. Thanks!
I'd probably go with creating custom data structures to model your scenario. For example.
Set class with a weight property and a reps property.
Exercise class with a name property and a collection of Sets.
Workout class with a collection of Exercises and a date property for when the workout was done.
That way, if you wanted to extend it to include food you eat that day, you could either add it to the workout, or probably a better option would be to compose another class of a Workout and food eaten.
That way you open the possibility to draw correlations between how well you trained on a certain day with what you eat.
-- I'm a C# developer and I haven't touched Java before so apologies if the Syntax or the types aren't correct --
public class Set {
public Set()
{
this._weight = 0;
this._reps = new ArrayList<int>();
}
private BigDecimal _weight;
private List<int> _reps;
// implement public properties / methods
}
public class Exercise {
public Exercise()
{
this._name = "";
this._sets = new ArrayList<Set>();
}
private String _name;
private List<Set> _sets;
// implement public properties / methods
}
public class Workout {
public Workout(Date workoutDate)
{
this._date = workoutDate;
this._exercises = new ArrayList<Exercise>
}
private Date _date;
private List<Exercise> _exercises;
// implement public properties / methods
}
Then you'd be able to store a List and order them by Date using a custom implementation of Comparator<Workout>

Converting an ArrayList<HashMap> into a multidimensional List

I have an ArrayList of HashMap elements that has a format of Category, Activity and Time. I.E.
{CATEGORY=Planning, ACTIVITY=Bills, TIME=5}
{CATEGORY=Planning, ACTIVITY=Bills, TIME=7}
{CATEGORY=Planning, ACTIVITY=Meetings, TIME=10}
{CATEGORY=Resources, ACTIVITY=Room1, TIME=15}
....
Take note of the CATEGORY/ACTIVITY pair that is repeated as that can happen in the List
I need to be able to convert this List into a multidimensional one. The best way I can think of for how this List needs to look is by writing some pseudocode...please see that at the bottom of the post.
I've thought of several different approaches on how to implement this but I'm quite frankly stuck and frustrated at how to do this. I've thought of taking the inefficient approach of looping through the ArrayList several times in outer and inner loops but I know that wouldn't be good coding practice.
Any suggestions on how I can implement this conversion so I can loop like in the pseudocode below?
For CATEGORY in CATEGORIES {
CategoryTime = 0
Display Category Header
For ACTIVITY in ACTIVITIES {
Activity Time = 0
For TIME_RECORD in ACTIVITY
Add time to activity total time, category total time & grand total
}
Display Activity Total
}
Display Category Total
}
Display Grand Total and rest of information...
Edit
I appreciate all the feedback given for this problem and it appears that really the best way to go is to enhance a class that the ArrayList of HashMap elements is a member of.
I've put in a vote to close this question as has another person as it's too localized. I would appreciate it if some of you other developers would follow suit to close the question. I would delete it but I can't at this point because there are answers to the question.
I would write a class that looks like so:
public class Planner
{
Map<Category, Collection<Planner> details;
String activity;
long time;
}
public enum Category
{
PLANNING,RESOURCES,ETC;
}
Then you should be able to do the following:
for(Category current: Planner.getDetails().keySet())
{
CategoryTime = 0
Display Category Header
Activity Time = 0
for(Planner currentPlanner : planner.getDetails().get(current))
{
currentPlanner.getActivity();
Activity Time += currentPlanner.getTime();
}
}
The problem you'll have with using the Collections API, besides a poor abstraction, is that you'll have to store many Activities for a given Category. If Category is the key, then you're forced to have a List<Activity> as the value in the Map. And if you query for a given Category, your work isn't done: you have to iterate over the List<Activity> to find the one you want. How will you know?
It's not a Map; it's a multi-map.
I agree with the folks who recommend a class. It's far better, and not that much more work. Better abstractions and more information hiding are usually better for you and your clients.
public class Activity {
private Category category;
private Duration duration; // You want to encapsulate value and units together, right?
// I can see sequencing information that could be useful. Your whole Planner seems to be in need of work.
}
I think your idea of time units is poorly done, too. I can't tell if TIME=10 means 10 hours, days, weeks, months, years, decades - you get the point. Units matter a lot, especially in this context. You would not want people to add times together that used different units.

Categories

Resources