Super deconstruction of very simple java code


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 8 of 8

Thread: Super deconstruction of very simple java code

  1. #1
    Join Date
    Jan 2006
    Posts
    7

    Arrow Super deconstruction of very simple java code

    hello! newbie here
    So I've come to realize that if I want to get many of my ideas going I need to learn programming.

    Many years ago, I took Java, now I am back at it, but this time straight to a 200 level, where it is assumed I know the basics. I have about 2 weeks until things really start moving, so right now I am reading and experimenting about for about 6 or so hours a day. I've been reading a good text, and been fairly coherent thus far 200 pages in, except for now they have thrown an example down without explaining half the stuff.

    I have some q's regarding this very simple example that uses 2 classes. Now, I like to analyze things waaay further than any book, so forgive me if I overkill the q's, but its also a bit of built up q's from previous pages. Hopefully there are some patient hackers around here

    My questions start with a “//###”


    Code:
    //********************************************************************
    //  CountFlips.java       Author: Lewis/Loftus
    //
    //  Demonstrates the use of a programmer-defined class.
    //********************************************************************
    
    public class CountFlips
    {
       //-----------------------------------------------------------------
       //  Flips a coin multiple times and counts the number of heads
       //  and tails that result.
    //### WHY do we need “(String[] args)”? rather than just ()?
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          final int NUM_FLIPS = 1000;
          int heads = 0, tails = 0;
    
          Coin myCoin = new Coin();  // instantiate the Coin object
    
          for (int count=1; count <= NUM_FLIPS; count++)
          {
             myCoin.flip();
    
             if (myCoin.isHeads()) 
                heads++;
             else
                tails++;
          }
    
          System.out.println ("The number flips: " + NUM_FLIPS);
          System.out.println ("The number of heads: " + heads);
          System.out.println ("The number of tails: " + tails);
       }
    }
    
    ********************************************************************
    //  Coin.java       Author: Lewis/Loftus
    //
    //  Represents a coin with two sides that can be flipped.
    //********************************************************************
    
    import java.util.Random;
    
    public class Coin
    {
       private final int HEADS = 0;
       private final int TAILS = 1;
    
       private int face;
    
       //-----------------------------------------------------------------
       //  Sets up the coin by flipping it initially.
    //
       //-----------------------------------------------------------------
       public Coin ()
       {
          flip(); 
       }
    
       //-----------------------------------------------------------------
       //  Flips the coin by randomly choosing a face value.
    	// ###BUT why does it need to be void?
    	// ###IS it public mainly because the above method is also public?
    // ###WHAT is with the *2 ?? and how does the function give a “HEADS or
    // TAILS kind of answer?
    //### why cant this method and the above flip() somehow be 
    //combined into one method??
       //-----------------------------------------------------------------
       public void flip ()
       {
          face = (int) (Math.random() * 2);
       }
    
       //-----------------------------------------------------------------
       //  Returns true if the current face of the coin is heads.
    //###really not seeing how face would equal
    // HEADS from above face calc.
    
       //-----------------------------------------------------------------
       public boolean isHeads ()
       {
          return (face == HEADS);     
       }
    
       //-----------------------------------------------------------------
       //  Returns the current face of the coin as a string.
    //
       //-----------------------------------------------------------------
       public String toString()
       {
          String faceName;
    
          if (face == HEADS)
             faceName = "Heads";
          else
             faceName = "Tails";
    
          return faceName;
       }
    }
    I guess that’s enough qs for now, thanks for any takers. My main confusion lies in how the face = (int) (Math.random() * 2 can return (face == HEADS) ????

    BTW: I did run this and it does work.

  2. #2
    Join Date
    Mar 2004
    Posts
    635
    1. flip() is void because it is not returning anything
    2. public allows anything to access the method. Click here for a complete explanation
    3. Math.random() returns a double between 0.0 and 0.9. Multiply that by 2 and your range is now 0.0 to 1.8. Cast that to an integer and it cuts off the fractional part leaving just a whole number. So the value of "face" will either be 0 or 1.
    4. Because the above "method" isn't a method. It has no return type. Instead, it is called the contructor. Note how it has the same name as the class.

  3. #3
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Quote Originally Posted by Phaelax
    3. Math.random() returns a double between 0.0 and 0.9. Multiply that by 2 and your range is now 0.0 to 1.8.
    No, Math.random() returns an double, where 0 < double < 1. When you multiply this by 2, you get 0 < double < 2.
    (yes, then it's casted to an int, either 0 or 1).

    I don't know if this was a question too, but I'll answer it anyway.
    face == HEADS; resolves to a boolean (true or false). if face equals heads,
    it's true, if face does not equals heads, it's false.
    Code:
    return face == HEADS;
    does the same things as
    Code:
    if (face == HEADS) {
        return true;
    } else {
        return false;
    }

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    WHY do we need ?(String[] args)?? rather than just ()?
    Thats just the way it is, its the defined java application entry point. It the same as the old C entry point, without the argument count parameter (its built into the java String array).

    When the application is executed from the command prompt like:
    Code:
    javac myApp  one two three
    ...the args array passed to the application will have three elements, "one", "two" and "three".
    eschew obfuscation

  5. #5
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    @WHY do we need “(String[] args)”? rather than just ()?
    See sjalle's post.

    Useful links:
    The Java(tm) Tutorial: The main Method
    The main Method
    The Anatomy of a Java Application
    Java Glossary: main

    @BUT why does it need to be void?
    because it's not returning anything. All it's doing is setting face to a value.

    Useful Links:
    The Java(tm) Tutorial: Returning a Value from a Method
    Java Glossary: void

    @IS it public mainly because the above method is also public?
    It is public so that other classes can use it (i.e. your CountFlips class). If it was private, only the Coin class would be able to use it.

    Useful links:
    The Java(tm) Tutorial: Controlling Access to members of a Class
    Java Glossary: public
    Code Guru: Java Access Specifiers

    @WHAT is with the *2 ?? and how does the function give a “HEADS or TAILS kind of answer?
    See my other post and/or Phaelax's post. HEADS and TAILS are final ints, which means they can't be changed. You're generating a number 0 (HEADS) or 1 (TAILS). Then, you can check whether face is heads or not, by doing (face == HEADS) (exlpained farther down)

    Useful Links:
    Code Guru: The final Keyword
    Java Glossary: final
    The Final Word on the final Keyword

    @why cant this method and the above flip() somehow be combined into one method??
    They could, but that wouldn't be helpful.
    Code:
    public Coin() {
        flip(); 
    }
    This is called constructor, whenever you do new Coin(), it allocates memory and flips the coin. It really doesn't need to though, it can be an empty constructor. It would be bad to do this though:
    Code:
    public Coin() {
        face = (int) (Math.random() * 2);
    }
    Because then, everytime you wanted to flip the coin, you wouldn't able to do coin.flip(), and you'd have to do:
    coin = new Coin();
    which allocates memory.

    Useful Links:
    The Java(tm) Tutorial: Understanding Instance and Class members
    The Java(tm) Tutorial: Creating Objects
    Java Glossary: new
    Java Glossary: constructors
    Java Programming Notes: Java Constructors
    Java 102: Dealing with Classes

    @really not seeing how face would equal HEADS from above face calc.
    It might not.
    (face == HEADS) is either true or false. if face does equal heads, it's true,
    if it doesn't it's false. the isHeads() method is just analyzing whether face is HEADS or not.

    Useful Links:
    Java Glossary: boolean
    Java Programming Notes: Java Boolean
    Last edited by destin; 01-14-2006 at 04:24 PM.

  6. #6
    Join Date
    Mar 2004
    Posts
    635
    Quote Originally Posted by destin
    No, Math.random() returns an double, where 0 < double < 1.
    From the java 1.4 api docs:
    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0
    0 <= double < 1

  7. #7
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    I stand corrected.

  8. #8
    Join Date
    Jan 2006
    Posts
    7
    thanks for the replies guys, that helped much

Similar Threads

  1. Re: C++ vs Java
    By Michael in forum Java
    Replies: 2
    Last Post: 12-31-2002, 04:55 PM
  2. Has Sun Given Up on the Desktop?
    By Lori Piquet in forum Talk to the Editors
    Replies: 114
    Last Post: 10-10-2002, 06:01 AM
  3. Replies: 1
    Last Post: 05-08-2002, 07:17 AM
  4. Simple question: MouseOver Java Code for Netscape
    By Craig in forum Architecture and Design
    Replies: 1
    Last Post: 04-22-2001, 01:04 PM
  5. Simple Java DOM question
    By Lenin in forum XML
    Replies: 0
    Last Post: 03-21-2001, 04:01 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center