How can i keep track of String values? - java

I'm building some kind of game for programming class and I need to have a history of the people who played, you can play multiple times when you run the game, so I'm not trying to store it permanently just when the game is executing.
I was thinking maybe some kind of array or something that can store all the string variables (names), but I don't how to do this indefinitely until the game stops.
Also, I am not allowed use java data structures (ArrayList, LinkedList, etc.)
.
Alternatively, if this is not possible or very complicated, maybe some way to store the names of only the last 10 people that play would work.
Any help is appreciated.

If data structures are not allowed, you could actually just make do of a comma-delimited String because an array in order to initialize you need to specify its size already (but this is something you definitely cannot know yet). Have a static instance of the String, then append to it a delimiter (comma) and the the player name.
private static String commaDelimitedStr = "";
public void addPlayerName (String playerName) {
commaDelimitedStr = commaDelimitedStr.concat(",").concat(playerName);
}
Then at the end you can split the String to get an array version of it.
String[] names = commaDelimitedStr.split(",");

Related

How to efficiently locally store instances of an object in Java

I am kind of a beginner in Java. I have this college project where we are asked to build a train booking system (desktop). As part of the app, the admin can add and edit new routes. I want to store those instances of different routes somewhere, but how? I want to be able to add as many as I want, but lists and arrays require for a size to be determined. How can I store indefinite instances of an object efficiently? This is the data I want to store for each instance:
int routeId;
String deptPoint;
String destPoint;
String transpMode;
int vehicleId;
Note: we must use Java data types, no DBs allowed.
Some help would be appreciated! Thanks :)
but lists and arrays require for a size to be determined.
Incorrect. Arrays have a set size, but not lists. A List implementation (if mutable) supports automatic dynamic resizing, up to a limit of two billion items or running out of memory.
Define your class. Here we use the records feature in Java
16+ for brevity. But if you need mutable objects, declare a conventional class instead.
record Route( int routeId, String deptPoint, String destPoint, String transpMode, int vehicleId ) {}
Declare a list to hold objects of that class.
List< Route > routes = new ArrayList<> () ;
Instantiate Route objects, and collect.
routes.add( new Route( … ) ) ;
In fact, Java lists are not requiring predetermined size, they will change as you add elements and remove them, so they're perfectly fine to store Java objects. Thing you didn't mention is do you need to persist it or not, if you don't need to then you can just do that. If you need to, you'll need database or store it to the file on your machine.
You could build an object that have this fields and put it in a List:
public class Route {
int routeId;
String deptPoint;
String destPoint;
String transpMode;
int vehicleId;
}
As deHaar suggested, one option would be to store your values in a text file with JSON format. You could use gson to convert to/from JSON really easy. You then only have to implement the mechanism to store this JSON in a local file following this example.

Java: Getting object associated with enum

I have an ArrayList full of custom objects. I need to save this ArrayList to a Bundle and then retrieve it later.
Having failed with both Serializable and Parcelable, I'm now simply trying to somehow save the objects that are associated with the indexes in the ArrayList, then checking these when restoring the Bundle and adding the objects back in.
What I have is something like this:
When saving the Bundle:
//Create temporary array of the same length as my ArrayList
String [] tempStringArray = new String[myList.size()];
//Convert the enum to a string and save it in the temporary array
for (int i = 0; i<myList.size();i++){
tempStringArray [i] = myList.get(i).getType(); //returns the enum in string form
}
//Write this to the Bundle
bundle.putStringArray("List", tempStringArray);
So I now have an array of strings representing the enum types of the objects that were originally in the ArrayList.
So, when restoring the Bundle, what I'm trying is something like this:
//Temporary string array
String[] tempStringArray = savedState.getStringArray("List");
//Temporary enum array
ObjectType[] tempEnumArray = new ObjectType[tempStringArray.length];
for (int i = 0; i<tempStringArray.length;i++){
tempEnumArray[i]=ObjectType.valueOf(tempEnemies[i]);
}
So, now I have the enum type of each item that was originally in the ArrayList.
What I'm now trying to do now, is something like (would go inside the for loop above):
myList.add(tempEnumArray[i].ObjectTypeThisEnumRefersTo());
Obviously the "ObjectTypeThisEnumRefersTo()" method above doesn't exist but this is ultimately, what I'm trying to find out. Is this possible or perhaps there is some other way of doing this?
To get an enum value of the enum type Enemy from a string, use
Enemy.valueOf(String).
Enemy.valueOf("SPIDER") would return Enemy.SPIDER, provided your enum looks like
enum Enemy { SPIDER, BEE};
EDIT: It turns out Zippy also had a fixed set of Enemy objects, each mapped to each value of EnemyType, and needed a way to find an Enemy from a given EnemyType. My suggestion is to create a
HashMap<EnemyType, Enemy>
and put all the objects in there upon creation, then at deserialization convert strings to enum values and enum values to Enemy objects using the hashmap.
It later occurred to me though that depending on how much logic you have in Enemy, you might want to consider scrapping either Enemy or EnemyType and combine them into one parameterized enum, similar to the example with Planet over here:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
That would spare you from having to go two steps from a string to your final object and simplify things a bit as you wouldn't need any hashmap after all.

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>

Java Dynamic Memory Allocation (Heap)

This isn't a question that I am expecting a specific answer to since it is pretty broad. I'm teaching myself Java and am focusing specifically on dynamic memory allocation. Let's make a very oversimplified example: Say that I have a really basic data entry screen. So basic that all that happens is the user enters a series of first names, maybe for an employee directory or something. On my JFrame, I have a single JTextField control where these names are entered. The number of employees is known only at run time. The user enters a name and hits the enter key, which commits the name to memory and creates a new object to store the next name (silly, I know, but I'm trying to focus). Something like this (don't take this too literally - I obviously didn't compile this):
public class Employee {
String fName;
public void setName( String n ) {
fName = n;
}
};
public class JFrameEmp {
//blah, blah, blah
JTxtName.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
/* Handle the enter key */
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
/* Store name */
this.setName(JTxtName.getText());
/* Create New Object */
Employee next = new Employee();
}
};
}
}
Where I need help is on the last line. Even if this were to work, let's say that I wanted to print out a list of the names entered. In my approach, I see no way to uniquely identify each object (so that I can iterate through them).
Do I need to create an array to store these? But that has a fixed length and lives on the stack. I'd rather find a way to use the heap to allow for an open-ended list.
What should I be reading to learn how to do this? It must be a very common thing to do, but the books that I have don't seem to cover it.
Thanks. I hope that I have explained this well enough without going into too much detail.
It sounds like you want to store a List of Employees. Java provides dynamically sized array with its ArrayList class.
Here is an example:
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee("Alice"));
employees.add(new Employee("Bob"));
System.out.println(employees.get(0)); // prints out Alice
You could use an array. You might find it useful to have a look at the Java Collections framework, in particular the page about the implementations.
But yes you will need to be adding the objects to some sort of data structure otherwise they will be getting cleaned up by the garbage collector after there is no valid reference to them.
It seems like you are looking for a data storage structure.
You could use a built in array, which is actually stored on the heap in java(the only issue is that you would have to keep track of size and reallocate when more space is needed).
A better option would be an ArrayList, which has built in add methods that automatically resize when needed.
You could also use a HashMap, which would allow to quickly search for your employees by name.

Categories

Resources