Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Instantiating an Array
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
hmafia




PostPosted: Fri Mar 04, 2011 3:03 pm   Post subject: Instantiating an Array

Hey guys I just need quick help instantiating an array.

What we had to do was build a hierarchy (UML), with 1 superclass and 3 other subclasses.

I've done all that, now I have to create a driver class to test all the classes I created.

Here's the instructions for the driver class.


1) Create an array of type Beverage named drinksArray, and size it to hold 3 Beverage objects.

Does this seem right ?


code:


public class CreateDrinks
{
       
        //Create an array of type Beverage named drinksArray, and size it to hold 3 Beverage objects.
       
        private Beverage[] drinksArray = new Beverage[3];
       



2) Instantiate the following three drinks and assign each one to an element of the array:

The first, drink1, is a HotDrink object, a coffee which comes in a pot that contains 1.5 litres, is best served at 80 degrees celsius and has a brand name of ?Folgers?.

code:
HotDrink drinkOne = new HotDrink("Coffee"       , "pot", "litres", 1.5, 80, "Folgers")
;

The second, drink2 is a ColdDrink, a soda which comes in a 710 ml bottle and is best served at 3 degrees celsius. The brand name is ?Pepsi?.

code:
ColdDrink drinkTwo = new ColdDrink("Soda", "bottle", "ml", 710, 3, "Pepso");


The third, drink3 is a Beer, a lager which comes in a 12 ounce can made by ?Labatts? (gotta support the local industry!), is best served at 3 degrees celsius, and has a 5 percent alcohol content. Remember that this class also contains a warning in its howToServe( ) method about the danger of over-indulging in this drink. See the sample printout on the next page.

code:
Beer drinkThree = new Beer("Lager", "can", "ounce", 12, 3, 5);



And:

code:
drinksArray[0] = drinkOne;
drinksArray[1] = drinkTwo;
drinksArray[3] = drinkThree;



3) Set up a loop that will have each array element in the array call its getDrinkDetails( ) method. This will cause polymorphic behavior to occur, because the JVM will have to determine at run time what type of object is making the method call.

Alright so let me know if what I've done in part 1 and 2 are correct.
I'm trying to figure out part 3 right now. Any help on righting the loop would be much appreciated !
Sponsor
Sponsor
Sponsor
sponsor
DemonWasp




PostPosted: Fri Mar 04, 2011 4:23 pm   Post subject: RE:Instantiating an Array

You're about 98% of the way there. Take a careful look at the last block of code you posted and I think you'll have a brief face-palm moment.
hmafia




PostPosted: Fri Mar 04, 2011 4:41 pm   Post subject: Re: Instantiating an Array

drinksArray[0] = drinkOne;
drinksArray[1] = drinkTwo;
drinksArray[3] = drinkThree;

Bolded part ?


I changed it, I noticed it seconds after posting the code here lol. So looks like this now.

code:
drinksArray[0] = drinkOne;
drinksArray[1] = drinkTwo;
drinksArray[2] = drinkThree
;

There seems to be an issue with my getDrinkDetails method, whenever I try running this code to test if it's working, I get a huge error.

code:
System.out.println(drinkOne.getDrinkDetails());


Here is the method ( written in the superclass then subclasses)


Superclass
code:
/*
         * MethodName: getDrinkDetails()
         * Purpose: To get specific details of each and every drink we create.
         * Accepts: nothing.
         * Returns: a concatenated String that lists the name,
         * container, measurement, volume, and temperature of the beverage
         */
       
        public String getDrinkDetails()
        {
                System.out.println("This drink is called " + this.name +        ", and comes in a " + this.volume + 
                                                                                                this.measurement + this.container + " and should be served at "  + this.temperature
                                                                                                + " degrees celsius.");
                return getDrinkDetails();
                                                                                       
        }



Subclass

code:
        /*
         * MethodName: getDrinkDetails()
         * Purpose: To get specific details of each and every drink we create.
         * Accepts: nothing.
         * Returns: a concatenated String that lists the name,
         * container, measurement, volume, brand, and temperature of the beverage
         */
        public String getDrinkDetails()
        {
                System.out.println("This drink is offered under the brand name " + this.brand);
               
                return getDrinkDetails();
        }
       



Error I get.

code:
This drink is offered under the brand name Folgers
This drink is offered under the brand name Folgers
This drink is offered under the brand name Folgers
This drink is offered under the brand name Folgers
Exception in thread "main" java.lang.StackOverflowError
        at sun.nio.cs.SingleByteEncoder.encodeArrayLoop(Unknown Source)
        at sun.nio.cs.SingleByteEncoder.encodeLoop(Unknown Source)
        at java.nio.charset.CharsetEncoder.encode(Unknown Source)
        at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
        at sun.nio.cs.StreamEncoder.write(Unknown Source)
        at java.io.OutputStreamWriter.write(Unknown Source)
        at java.io.BufferedWriter.flushBuffer(Unknown Source)
        at java.io.PrintStream.write(Unknown Source)
        at java.io.PrintStream.print(Unknown Source)
        at java.io.PrintStream.println(Unknown Source)
        at HotDrink.getDrinkDetails(HotDrink.java:46)
        at HotDrink.getDrinkDetails(HotDrink.java:48)
        at HotDrink.getDrinkDetails(HotDrink.java:48)
        at HotDrink.getDrinkDetails(HotDrink.java:48)
        at HotDrink.getDrinkDetails(HotDrink.java:48)
        at HotDrink.getDrinkDetails(HotDrink.java:48)
Tony




PostPosted: Fri Mar 04, 2011 4:48 pm   Post subject: RE:Instantiating an Array

You do indeed have a java.lang.StackOverflowError error. Read the entire error message to get the line number (it's 48).
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
hmafia




PostPosted: Fri Mar 04, 2011 5:05 pm   Post subject: RE:Instantiating an Array

I know, how do I fix it ?
Tony




PostPosted: Fri Mar 04, 2011 6:21 pm   Post subject: RE:Instantiating an Array

If you have to ask, then you don't really "know". Not having infinite loops will help.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
DemonWasp




PostPosted: Fri Mar 04, 2011 8:00 pm   Post subject: RE:Instantiating an Array

Here's a hint: Drink.getDrinkDetails() calls Drink.getDrinkDetails() calls Drink.getDrinkDetails() calls Drink.getDrinkDetails() calls ...
hmafia




PostPosted: Fri Mar 04, 2011 9:14 pm   Post subject: RE:Instantiating an Array

Yea i understand that it's an infinited loop, i'm working on fixing that..

I'm assuming I created a recursive method.


Does this work better?

code:
public String getDrinkDetails()
        {
                String drinkDetails = "This drink is called " + this.getName() +        ", and comes in a " + this.getVolume() +                                                  this.getMeasurement() + this.getContainer() + " and should be served at "  + this.getTemperature()                                                + " degrees celsius.";
                return drinkDetails;
               
                                                                                       
        }



I'm trying to figure out how to set up the loop in my driver class.

Thanks guys
Sponsor
Sponsor
Sponsor
sponsor
DemonWasp




PostPosted: Sat Mar 05, 2011 1:08 am   Post subject: RE:Instantiating an Array

You created a recursive method, yes. Generally the trick is that you want some invocation to eventually return without calling itself again, so that the returns can go up the "chain" of invocations.

Yes, that method will work better. However, better formatting would be a good choice. You don't need to keep everything on one line -- that's why Java ends each statement with a semicolon ( ; ).

Something you may want to do is the following:
code:

// In Beer...
public String getDrinkDetails() {
    return super.getDrinkDetails() +
        "; it contains 5% alcohol by volume";
}


code:

// In Drink
public String getDrinkDetails() {
    return "This drink is called " + this.getName() + ", ...";


Then when you call Drink.getDrinkDetails(), if the object is an instance of Beer, then it will call Beer.getDrinkDetails(). The first thing that method does is get the result of super.getDrinkDetails(), which turns out to be Drink.getDrinkDetails(). Then, it adds details specific to that kind of drink.

This lets you write the code for outputting the details in Drink exactly once, but use them in every descendent class. Just be careful to call super.getDrinkDetails(), or you'll fall back into the recursive infinite loop you have right now.
hmafia




PostPosted: Sat Mar 05, 2011 4:31 pm   Post subject: RE:Instantiating an Array

Wow makes total sense, fixed it all and it's not working perfectly fine. The loop part was actually not that hard at all so got that figured out this morning.

Anyway, thanks a lot the both of you , helped me out tremendously. Cheers.

EDIT: any chance some mod could delete this topic for copyright reasons, I don't want to take a chance.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 10 Posts ]
Jump to:   


Style:  
Search: