Java OOP: Building Object Trees / Object Families - java

Been a while since I used Java and was wondering if this was a decent or even correct way of setting this up.
FYI, userResults refers to a JDBI variable that isn't present in the code below.
Feel free to suggest a better method, thanks.
public class Stat
{
private int current;
private int max;
public int getCurrent() {return current;}
public void setCurrent(int current) {this.current = current;}
public int getMax() {return max;}
public void setMax(int max) {this.max = max;}
}
public class Character
{
Stat hp = new Stat();
Stat mp = new Stat();
}
Character thisCharacter = new Character();
// Set the value of current & max HP according to db data.
thisCharacter.hp.setCurrent((Integer) userResults.get("hpColumn1"));
thisCharacter.hp.setMax((Integer) userResults.get("hpColumn2"));
// Print test values
System.out.println (thisCharacter.hp.Current);
System.out.println (thisCharacter.hp.Max);

Correct? Well, does it work? Then it probably is correct.
Wether or not it is a decent way to do it then the answer is "maybe". It is hard to tell from what context this code is in. But there are some things you could keep in mind though:
In which class (or object rather) are the Stat set in? Do you feel is it the responsibility of the class to do this and know what database values to get them from? If not, consider making some kind of a class that does this.
Making chained calls such as thisCharacter.hp.setCurrent(...) is a violation of principle of least knowledge. Sometimes you can't help it, but usually it leads to kludgy code. Consider having something that handles all the logic surrounding the stats. In your code you may need a HealthStatsHandler that have methods such as loadStats(), saveStats(), and mutator actions such as takeDamage(int dmg) and revive(int health).
If you have trouble figuring things out if it has the correct object design, then study up on the SOLID principles. They provide nice guidelines that any developer should follow if they want to have code that is extensible and "clean".

This is not really a tree. It is not possible two have more than one layer of children.
Usually you define an interface let's call it Node where both Stat and Character implements it and the two children of Character would have the type Node.

I would consider creating the Stat objects seperately and passing them into Character, and making the character attributes private as follows:
public class Character
{
private Stat hp;
private Stat mp;
public Stat getHp() {return hp;}
public void setHp(Stat h) {this.hp = h;}
public Stat getMp() {return mp;}
public void setMp(Stat m) {this.mp = m;}
}
// Set the value of current & max HP according to db data.
Stat hp = new Stat();
hp.setCurrent((Integer) userResults.get("hpColumn1"));
hp.setMax((Integer) userResults.get("hpColumn2"));
Character thisCharacter = new Character();
thisCharacter.setHp(hp);
// do the same for mp
One additional simple step would be to create a Character constructor that would take an hp and an mp

Related

How to find number of live objects in a Java application without using any tool? [duplicate]

This question already has an answer here:
How to get jmap histogram programmatically?
(1 answer)
Closed 7 years ago.
Is there a way to find no. of alive objects of a class at any point of time in a running application? By alive/live objects, I mean those objects which are NOT eligible for garbage collection. Is there any way to find it without using any tools?
Assume that the entire application is personally coded. So the classes can be customised as per our need. Also, assume that the class whose live instance count we want to find, is a user defined class, not any inbuilt class.
The simple answer is no - there is no simple class or method call to make to find this data. However, there are many ways that people have come up with. It depends on why you need the data and the structure of your program.
There are good discussions on this topic here: http://www.coderanch.com/t/581790/java/java/ways-find-number-alive-instances and here: How to find the number of objects in the heap.
Give some of those a try and see which works best for you.
Yes.
Create a class based static instance counter that is synchronous
Up it by one in the class method(s) that instantiate..
Then u will have to override the dispose method to decrement instance counter..
UPDATE
Here is a nebulous class.. that can be used to track some things...
package myclasses;
import java.util.Vector;
public class ClassA {
private static int iCountInstances = 0;
private static int iCountCleanups = 0;
private static int iCountGCFinalize = 0;
private String m_str1 = null;
private Vector m_vct1 = null;
public ClassA() {
// bump the instance count
incrementCountInstance();
}
private static synchronized void incrementCountInstance() {
iCountInstances++;
}
private static synchronized void incrementCountCleanup() {
iCountCleanups++;
}
private static synchronized void incrementGCFinalize() {
iCountGCFinalize++;
}
/**
* reportOut - you can change this up on how ever you like
*
* an in control app in a perfect world will have all three counts THE SAME after a final
* GC and right before exist.
*
* The True number of 'active' classes in an app is going to be
* ICountInstances - iCountGCFinalize.
*
* The idea here is that if GC did not dispose of it.. its still in memory.. and still
* active.. even if your app thinks its no longer using it...
*
* #return
*/
public static String reportOut() {
return "ClassA Counts: incnt:" + ClassA.iCountInstances +", clncnt:" + ClassA.iCountCleanups + ", gccnt:" + ClassA.iCountGCFinalize;
}
public void cleanup() {
//
// ok.. initialize all member variables here
// do not worry about what other object refereneces this guy
// you only care about what you have as member variables.
// you only de-refrence what you point to ..
// if every class took care of what it referenced.. then all is well.
// so.. clean up your object and help GC ...
this.setM_str1(null);
this.getM_vct1().removeAllElements();
ClassA.incrementCountCleanup(); // Increment the cleanup count..
//
// feel free to write to a logger reporting out that programmer has cleaned up this instance..
//
}
#Override
protected void finalize() throws Throwable
{
// Incrementing means GC determined this guy is truly an Object Orphan and has been
// completely de-referenced.
ClassA.incrementGCFinalize();
//
// feel free to write to a logger reporting out that GC is removing this instance..
//
}
public String getM_str1() {
return m_str1;
}
public void setM_str1(String m_str1) {
this.m_str1 = m_str1;
}
public void setM_vct1(Vector m_vct1) {
this.m_vct1 = m_vct1;
}
public Vector getM_vct1() {
return m_vct1;
}
}
Here is another class that can be made to help report out whats going on during execution.. etc..
package myclasses;
public final class CheckCounts {
// No create instance allowed..
private CheckCounts() {
}
/**
* Report out on interesting counts...
*/
public static void reportOut() {
/// Add all the reportouts here..
System.out.println(ClassA.reportOut());
}
}
You can get fancy with this and create a background thread monitor that simply reports out stats on the classes you want to track.. and have it write to a logger every 30 seconds or so..
Notice I count up everything. You can use math to see how effective your code is at cleaning up after itself.. When you clean up an object.. you want to dereference what that objected pointed to and clear out any lists, arrays, hashmaps, etc. Be careful though, dont go crazy, and start cleaning up objects that live in a Vector of your class - just clean up the vector itself...
Give it a try.. its easy to implement.. and it may help you see whats going on in a runtime env vs what you think is happening just by looking at your code..

Reading information to a map

I'm learning about Sets and Maps in the Introduction to Java Programming book by Daniel Liang. My professor has assigned a problem in the back of the chapter that asks me to create a program that:
Queries the user for input on name
Queries the user for gender
Using these two criteria, and this/these website(s): http://cs.armstrong.edu/liang/data/babynamesranking2001.txt
... http://cs.armstrong.edu/liang/data/babynamesranking2010.txt
I have to be able to get the ranking.
I'm supposed to get this information into an array of 10 maps.
Each map corresponds with a .txt file/year. This is where I'm having problems with. How do I do this?
The (Int) rank of the student is the value of the map, and the key is the name (String) of the baby.
The way I was thinking was to create an array of maps or maybe a list of them. So like:
List<Map<Int, String>> or <Map<Int, String>[] myArray;
Yet even after that the issue of how I get all of this information from the .txt file to my maps is a hard one for me.
This is what I've come up so far. I can't say I'm happy with it. It doesn't even work when I try to start reading information is because I haven't specified the size of my array.
public class BabyNamesAndPopularity
{
public static void main (String[] args) throws IOException
{
Map<Integer, String>[] arrayOfMaps;
String myURL = "cs.armstrong.edu/liang/data/babynamesranking2001.txt";
java.net.URL url = new java.net.URL(myURL);
Scanner urlInput = new Scanner (url.openStream());
while(urlInput.hasNext())
{
...
}
}
}
Would it be viable to make a set OF MAPS? I was kind of thinking it would be better to make a set OF maps because of the fact that sets expand as needed (according to the load factor). I just need some general guidance. Unfortunately the CS program at my university (Francis Marion University in Florence, SC) is VERY small and we don't have any tutors for this stuff.
This answer rather vague, because of broad nature of question, and it may be more suitable for
programmers SE site. Still, you may find these two points worth something.
Instead of thinking in terms of 'raw' compound collections, such as lists of maps of sets or such, try to invent set of domain types, which would reflect your problem domain, and, as the next step, implement these types using suitable Java collections or arrays.
Unit-testing and incremental refinement. Instead of immediately starting with access to remote data (via java.net.URL), start with static source of data. Idea here is to have 'reliable' and easily accessible input data hand, which would allow you to write unit tests easily and w/o access to network or even to file system, using set of domain types from 1st point, above. As you write unit tests you can invent necessary domain types/methods names in unit tests at first, then implement these types/methods, then make unit tests pass.
For example, you may start by writing following unit test (I assume you know how to organize your Java project in your IDE, so unit test(s) can be run properly):
public class SingleFileProcessingTest {
private static String[] fileRawData;
#BeforeClass
public static void fillRawData() {
fileRawData = new String[2];
// values are from my head, resembling format from links you've posted
fileRawData[0] = "Jacob\t20000\tEmily\t19999";
fileRawData[1] = "Michael\t18000\tMadison\t17000";
}
#Test
public void test() {
Rankings rankings = new Rankings();
rankings.process(fileRawData);
assertEquals("Jacob", rankings.getTop().getName());
assertEquals("Madison", rankings.getScorerOfPosition(4).getName());
assertEquals(18000, rankings.getScoreOf("Michael"));
assertEquals(4, rankings.getSize());
}
}
Of course, this won't even compile -- you need to type in code of Rankings class, code of class returned by getTop() or getScorerOfPosition(int) and so on. After you made this compile, you'll need to make test pass. But you get main idea here -- domain types and incremental refinement. And easily verifiable code w/o dependencies on file system or network. Just plain old java objects (POJOs). Code for working with external data sources can be added later on, after you get your POJOs right and make tests, which cover most parts of your use cases, pass.
UPDATE Actually, I've mixed up levels of abstraction in code above: proper Rankings class should not process raw data, this is better to be done in separate class, say, RankingsDataParser. With that, unit test, renamed to RankingsProcessingTest, will be:
public class RankingsProcessingTest {
#Test
public void test() {
Rankings rankings = new Rankings();
rankings.addScorer(new Scorer("Jacob", 20000));
rankings.addScorer(new Scorer("Emily", 19999));
rankings.addScorer(new Scorer("Michael", 18000));
rankings.addScorer(new Scorer("Madison", 17000));
assertEquals("Jacob", rankings.getTop().getName());
// assertEquals("Madison", rankings.getScorerOfPosition(4).getName());
// implementation of getScorerOfPosition(int) left as exercise :)
assertEquals(18000, rankings.getScoreOf("Michael"));
assertEquals(4, rankings.getSize());
}
}
With following initial implementation of Rankings and Scorer, this is actually compiles and passes:
class Scorer {
private final String name;
private final int rank;
Scorer(String name, int rank) {
this.name = name;
this.rank = rank;
}
public String getName() {
return name;
}
public int getRank() {
return rank;
}
}
class Rankings {
private final HashMap<String, Scorer> scorerByName = new HashMap<>();
private Scorer topScorer;
public Scorer getTop() {
return topScorer;
}
public void addScorer(Scorer scorer) {
if (scorerByName.get(scorer.getName()) != null)
throw new IllegalArgumentException("This version does not support duplicate names of scorers!");
if (topScorer == null || scorer.getRank() > topScorer.getRank()) {
topScorer = scorer;
}
scorerByName.put(scorer.getName(), scorer);
}
public int getSize() {
return scorerByName.size();
}
public int getScoreOf(String scorerName) {
return scorerByName.get(scorerName).getRank();
}
}
And unit test for parsing of raw data will start with following (how to download raw data should be responsibility of yet another class, to be developed and tested separately):
public class SingleFileProcessingTest {
private static String[] fileRawData;
#BeforeClass
public static void fillRawData() {
fileRawData = new String[2];
// values are from my head
fileRawData[0] = "Jacob\t20000\tEmily\t19999";
fileRawData[1] = "Michael\t18000\tMadison\t17000";
}
#Test
public void test() {
// uncomment, make compile, make pass
/*
RankingsDataParser parser = new RankingsDataParser();
parser.parse(fileRawData);
Rankings rankings = parser.getParsedRankings();
assertNotNull(rankings);
*/
}
}

Sorting Arraylists of custom objects without using interfaces

Sorry, this might be duplicated, I'm not sure if my previous attempt to post this went through.
Started to learn Java several weeks ago, working on one of my first assignments. :)
My question is somewhat basic, but I couldn't find its exact equivalent after looking through previously resolved topics. This isn't a real life problem, so I guess it's expected from me to tackle it in a very specific way.
So the task consisted of several steps - I had to create a superclass with a number of custom objects, add new subclasses, implement new methods to count the value of certain variables, write test classes and sort my output.
It's all been done apart from this last step. Not sure if I'm allowed to just post my problems like that on the web, but here is where I am right now:
I have something like:
public class Pants
{
public enum SizeType {SMALL, MEDIUM, LARGE, EXTRA_LARGE}
private SizeType size;
private String brand;
private String countryOfOrigin;
private String color;
private double price;
//Other variables and methods
}
public class Jeans extends Pants
{
//new variables and methods
}
public class Shorts extends Pants
{
//some more new variables and methods
}
And other similar subclasses.
import java.util.ArrayList;
public class Selection
{
public static void main(String[] args){
Jeans ex1 = new Jeans("John Lewis");
ex1.countryOfOrigin("US");
ex1.color("Navy");
ex1.setSize(Pants.SizeType.LARGE);
ex1.setprice(40);
ex1.machineWashable(true);
System.out.println(ex1);
Shorts ex2 = new Shorts("Ted Baker");
ex2.countryOfOrigin("United Kingdom");
ex2.color("White");
ex2.setSize(Pants.SizeType.MEDIUM);
ex2.setprice(30);
ex2.machineWashable(true);
System.out.println(ex2);
//..etc
ArrayList<Pants> selection = new ArrayList<Pants>();
selection.add(ex1);
selection.add(ex2);
selection.add(ex3);
selection.add(ex4);
selection.add(ex5);
System.out.println( "Size - LARGE: " );
System.out.println();
Pants.SizeType size;
size = Pants.SizeType.LARGE;
ListPants(selection,size);
I need to write a ListPants method to list objects depending on SizeType - starting with large in this case. I don't think I can implement any additional interfaces (which is what was mostly recommended in other threads).
Please see my attempt below (didn't work). Am I thinking in the right direction here, or?
public static void ListPants(ArrayList<Pants> selection, Pants.SizeType size)
{
for (Pants.SizeType sizeType : Pants.SizeType.values()) {
for (Pants pants : selection) {
if (pants.getSize().equals(sizeType)) {
System.out.println(selection.toString());
I think it's just a minor problem you're facing. You already defined the signature of the method which should print out all pants of a specific size:
ListPants(ArrayList<Pants> selection, Pants.SizeType size)
That is correct. Now, your code is looping over all pants and over all possible sizes:
public static void ListPants(ArrayList<Pants> selection, Pants.SizeType size)
{
for (Pants.SizeType sizeType : Pants.SizeType.values()) {
for (Pants pants : selection) {
if (pants.getSize().equals(sizeType)) {
System.out.println(selection.toString());
Since this looks like a homework assignment, i'll phrase my answer as a question:
Where are you using the size parameter in the method body of ListPants?
I am assuming your class cannot implement new interfaces, and not using interfaces at all.
You can use Collections.sort(List,Comparator) with a Comparator, which is built for your class.
Something like
Collections.sort(selection,new Comparator<Pants>() {
#Override
public int compare(Pants p1, Pants p2) {
//implement your compare method in here
...
}
});
If you are eager to create your own sorting algorithm, have a look of this list of sorting algorithms. Simplest to implement (though pretty slow) IMO is selection-sort

Is this a valid use of the builder pattern in Java (or even good OO design)?

Being fairly new to OO, I often feel I understand a concept until I try to move from a simplified example to actual requirements I am given. I'd appreciate any help understanding how to think about this particular problem.
I have a GUI which has a panel that defines a container and items that go in it. Right now, there are three types of containers. The containers have some properties (like size) and can contain one to three different types of items (two are optional). Once enough information is entered, I use the information to make a graph.
I implemented an Observer pattern. When the user enters information, it updates an observable, which notifies the graph that it has changed.
I'm happy so far. Now the wrinkles. My containers have a size, but sometimes it is entered explicitly and sometimes it is determined by what the container is holding. That is determined by the type of container. How the size is determined, if not entered explicitly, depends on whether one of the optional items is in the container. I'm not sure if the requirements writer just hates me or I am lacking enough OO experience, but those wrinkles are giving me fits. Right now, my observable just has variables to hold all the assorted information and I use a bunch of switch statements to handle the special cases.
I am thinking that I could use the builder pattern. The director would produce the data that was graphed. I would have a concrete builder for each type of container and I would instantiate the class with the container properties and the items inside it. I would have methods of the abstract builder class to return to the director the values needed for the graph, for example getContainerSize() and combine these to produce the actual data points. Also, the director could return null if the user had not yet entered enough data to complete a graph.
Am I getting close to a usable OO design? I'm not sure I didn't just bury the special casing a bit deeper.
One other wrinkle. One of the item types goes in all three containers. Right now, my observable keeps track of the container and items separately and the method that creates the graph decides what to ask for (the graph changes a lot as users play around with the values). How's that work if I have multiple builder patterns?
Maybe I am missing a step? The observable updates the builder of the current container then lets the graph know it should call the director to get its coordinates? Which would then also need to ask what the current container was?
All comments welcome that help me get my head around OO design or this problem in particular. The actual requirements have more special cases, but are variations on this basic theme.
Thanks for the replies. I think I am guilty of mixing two questions together. Here is an attempt to provide a minimal code example focusing on the Builder pattern. Note IE8 I see no identation, FireFox 8, I do- so sorry to anyone reading the code in IE8.
interface MyContainerBuilder
{
void setContents( MyContents contents );
Double myVolume();
Double myDensity();
}
class SmallContainerBuilder implements MyContainerBuilder
{
Double volume = null;
Double density = null;
MyContents contents = null;
public void setVolume()
{
if (contents != null)
{
volume = contents.myDensity() / 3.0;
}
}
public void setContents( MyContents contents )
{
this.contents = contents;
}
public Double myVolume()
{
if (volume == null)
setVolume();
return volume;
}
public Double myDensity()
{
return contents.myDensity();
}
}
class BigContainerBuilder implements MyContainerBuilder
{
Double volume = null;
Double density = null;
MyContents contents = null;
public void setVolume( Double volume )
{
this.volume = volume;
}
public void setContents( MyContents contents )
{
this.contents = contents;
}
public Double myVolume()
{
return volume;
}
public Double myDensity()
{
return contents.myDensity();
}
}
class ContainerDirector
{
Double myResult( MyContainerBuilder container )
{
return container.myVolume() * container.myDensity();
}
}
class MyContents
{
Double density;
MyContents( Double density )
{
this.density = density;
}
public Double myDensity()
{
return density;
}
}
class Test
{
public static void main(String[] args)
{
SmallContainerBuilder smallContainer = new SmallContainerBuilder();
BigContainerBuilder bigContainer = new BigContainerBuilder();
ContainerDirector director = new ContainerDirector();
//
// Assume this comes from the GUI, where an ActionListener knows which Builder
// to use based on the user's action. I'd be having my observable store this.
Double density = 15.0;
MyContents contents = new MyContents( density );
smallContainer.setContents( contents );
//
// Then I would need to tell my observer to do this.
Double results = director.myResult( smallContainer );
System.out.println( "Use this result: " + results );
}
}
I have two types of containers that use a different method to calculate the volume. So let's say I have radiobuttons to select the container type and under each radiobutton a combobox of items that can go in the selected container. The ActionListener on the combobox will put the item in the right container and save it to my observable (there are lots of other things that actually get set) and it tells my observer to use the director to get an appropriate value and the observer then updates some view component of the GUI.
My containers have a size, but sometimes it is entered explicitly and sometimes it is determined by what the container is holding. That is determined by the type of container. [...] if not entered explicitly, depends on whether one of the optional items is in the container.
Sounds like you could have different subclasses of an abstract container, each implementing getContainerSize() in a different way. One for explicitly entered, one for the case with optional item and one without it.
... and I use a bunch of switch statements to handle the special cases.
Does not sound great. Replace Conditional with Polymorphism if applicable.
I am thinking that I could use the builder pattern...
I assume that you need to determine a concrete type of object (or null) based on a set of input variables. The pattern provides a way to build a complex object if it knows what type that is, but the actual problem is to decide which type. So you need conditional code at some place. That place can be a builder but it could be simple factory as well.
Right now, my observable keeps track of the container and items separately[...] observable updates the builder of the current container[...] How's that work if I have multiple builder patterns?
Not really understanding what that Observable is observing and what changes in which case are triggering what, but Observable updating a builder (or multiple) sounds strange. That's more of a gut feeling though :)
Am I getting close to a usable OO design?
If it works, yes. But I actually can't tell you if you have created a good or usable design because I still don't know the details of your problem or your design - after reading your text several times now.
Instead of adding another page of information to your question now, try to break your problem down into smaller pieces and use code snippets / images / graphs or any type of visualization to help people understand your problem and all the connections between those pieces. Just a lot of text is rather scary and a huge OO design like that is as a whole too big and too localized for SO.
Your approach seems fine but it requires IMO quite complex Objects to justify that use.
You create a MyContents instance in your GUI via the observer. That object is then wrapped in a MyContainerBuilder which is then given to a ContainerDirector which then produces a result. That is in my opinion one step too much if MyContents or the result is simple.
Also the way you set the MyContents to the MyContainerBuilder means that you can't reuse the same concrete MyContainerBuilder instance blindly. You either have to make sure that you use it sequentially or you have to construct a new one every time.
I.e this does not work
MyContents content1 = new MyContents( 5 );
MyContents content2 = new MyContents( 6 );
smallContainer.setContents( content1 );
smallContainer.setContents( content2 ); // overwriting old state
Double results1 = director.myResult( smallContainer ); // wrong result
Double results2 = director.myResult( smallContainer );
I assume that MyContents is a generic data holding object that is filled with data in several steps by the user. Once the user is happy with it, it is submitted to be build into a result. As far as I can tell, you know at that point what the result has to be.
Below is an approach using a Strategy Pattern(? - I'm bad with all those names and little differences) which I chose to plug into the MyContents directly so the MyContents object once finalized has all details how it has to be transformed into a result. That way safes one step and you don't need to create / maintain extra builder objects. MyContents is already in a way a Builder now.
interface VolumeStrategy {
Double calculateVolume(Double density);
}
class SmallVolumeStrategy implements VolumeStrategy {
public Double calculateVolume(Double density) {
return density / 3.0;
}
}
class BigVolumeStrategy implements VolumeStrategy {
public Double calculateVolume(Double density) {
return density;
}
}
class ContainerDirector {
Double myResult( MyContents container ) {
Double density = container.myDensity();
VolumeStrategy strategy = container.myStrategy();
return density * strategy.calculateVolume(density);
}
}
class MyContents {
// built via observer
Double density;
MyContents( Double density ) {
this.density = density;
}
public Double myDensity() {
return density;
}
// plugged in at the end.
VolumeStrategy strategy;
public void setStrategy(VolumeStrategy strategy) {
this.strategy = strategy;
}
public VolumeStrategy myStrategy() {
return strategy;
}
}
public class Test {
public static void main(String[] args) {
// all those can be static
VolumeStrategy smallStrategy = new SmallVolumeStrategy();
VolumeStrategy bigStratetgy = new BigVolumeStrategy();
ContainerDirector director = new ContainerDirector();
// from the GUI
Double density = 15.0;
MyContents contents = new MyContents( density );
// building this contents ...
// ... time to submit, we know what strategy to use
contents.setStrategy(smallStrategy);
// can turn contents into result without needing to know anything about it.
Double results = director.myResult( contents );
System.out.println( "Use this result: " + results );
}
}
That's a way what I think should work well for the problem I imagine you have. I can be wrong tough.

Array parameter passing

I'm in a beginner's java class. This Lab is for me to make a class "Wallet" that manipulates an array that represents a Wallet. Wallet contains the "contents[]" array to store integers represing paper currency. The variable "count" holds the number of banknotes in a wallet. After writing methods (that match provided method calls in a serpate Driver class) to initialize the Wallet and add currency/update "count", I need to transfer the array of one instantiated Wallet to another. I don't know how that would work because the one Wallet class has only been messing with a wallet called "myWallet" and now I need to take a new Wallet called "yourWallet" and fill it with "myWallet"'s array values.
//I should note that using the Java API library is not allowed in for this course
My Wallet class looks like this so far:
public class Wallet
{
// max possible # of banknotes in a wallet
private static final int MAX = 10;
private int contents[];
private int count; // count # of banknotes stored in contents[]
public Wallet()
{
contents = new int[MAX];
count = 0;
}
/** Adds a banknote to the end of a wallet. */
public void addBanknote(int banknoteType)
{
contents[count] = banknoteType;
count = count + 1;
}
/**
* Transfers the contents of one wallet to the end of another. Empties the donor wallet.
*/
public void transfer(Wallet donor)
{
//my code belongs here
}
...
The Driver code looks like this:
public class Driver
{
public static void main(String args[])
{
Wallet myWallet = new Wallet();
myWallet.addBanknote(5);
myWallet.addBanknote(50);
myWallet.addBanknote(10);
myWallet.addBanknote(5);
System.out.println("myWallet contains: " + myWallet.toString());
// transfer all the banknotes from myWallet to yourWallet
Wallet yourWallet = new Wallet();
yourWallet.addBanknote(1);
yourWallet.transfer(myWallet);
System.out.println("\nnow myWallet contains: "
+ myWallet.toString());
System.out.println("yourWallet contains: "
+ yourWallet.toString());
I want to use addBanknote() to help with this, but I don't know how to tell the transfer() method to transfer all of myWallet into yourWallet.
I had the idea to do somethign like this in transfer():
yourWallet.addBanknote(myWallet.contents[i]);
with a traversal to increase i for myWallet contents. It seems horribly wrong, but I'm at a complete loss as to write this method.
If my problem is so unclear that nobody can help, I would be more than happy to receive advice on how to ask a better question or on how to search with correct terms.
Thanks for any help you can provide.
I don't want to spoil your homework as you seem to be going the right way, but I do have some comments which you may either take or not :)
First, I would probably put the bank note types in some enumeration. But as that sounds a bit to advanced, consider
public class Wallet {
public static final int ONE_DOLLAR_BILL = 1;
public static final int FIVE_DOLLAR_BILL = 5;
...
// looks a bit more readable to me
myWallet.addBanknote(ONE_DOLLAR_BILL);
Transferring all the banknotes from the donor to yourself should not be so much of a problem
(a for loop would do) but I think you're in a world of hurt if you are trying to implement a
removeBanknote(int banknoteType);
as you are using count not only as a length but also as an index variable. By this I mean that you assume contents[0] ... contents[count-1] hold valid banknotes. And how do you remove one without too much work?
Warning: a bit more advanced
In your case I would probably opt to have a banknoteType of 0 indicating an empty banknote slot in your wallet, and implement _addBanknote(int banknoteType) as:
public void addBanknote(int banknoteType) {
for (int i=0; i < contents.length; i++) {
if (contents[i] == 0) {
contents[i] = banknoteType;
count++;
return; // OK inserted banknote at the first empty slot
}
}
throw new RuntimeException("Wallet is full");
}
This may be a bit overwhelming at this point. But it would allow you to implement:
public void removeBanknote(int banknoteType) {
for (int i=0; i < contents.length; i++) {
if (contents[i] == banknoteType) {
contents[i] = 0; // better: NO_BANKNOTE = 0
count--;
return;
}
}
throw new RuntimeException("This wallet does not contain a banknote of type " + banknoteType);
}
Please note that in both methods I return when I successfully removed or added the banknote. Only when I could not find a free slot, or the requested banknote, I finish the for loop and end up throwing an exception and thereby stopping the program.
I think the question is fine and I think you're on the right path. The way you're calling Wallet#addBanknote(int) is correct. What you have said is the right thing:
public void transfer(Wallet donor)
{
// Traverse the donor's wallet
// Add the bank note from the donor to this wallet
// What do you think also needs to happen to make sure
// the donor is actually giving their bank note?
}
Just another thing, what would happen in your Wallet#addBanknote(int) method if you have more contents than the MAX?
You can create either a constructor that takes another wallet, or a function (as already mentioned) and use System.arraycopy to copy the array in one fell swoop. System.arraycopy is fast, and its definitely overkill for something small like this, but its good tool to have in your toolkit.
The other alternative mentioned, copy the elements from one array to the other element by element in a loop will work fine too.
The myWallet inside the transfer method is named 'donor', and with that, it doesn't look horribly wrong:
addBanknote (donor.contents [i]);
You just need a loop around it, and to remove the yourWallet. which is the name of an instance of that class. That instance is inside the Class/method this, but needn't be specified, because there is no other addBanknote-Method in scope, which could be meant. (Thanks to mangoDrunk).

Categories