Basic Classes (Part 2)

I am continuing work with custom classes and OOP. I find that
I can't get eventlisteners and other actions to work unless I use
nested functions (which I know are frowned upon). The following
works correctly but the mouse event listener is an example nested
functions mentioned above. How can I rewrite this without the
nested function that executes the mouse listener? Thanks as always.
package {
import flash.display.MovieClip;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.MouseEvent;
public class Index extends MovieClip {
public function Index() {
var D:MovieClip = new dMC();
D.x = 100;
D.y = 275;
addChild(D);
var dtext:MovieClip = new dText();
dtext.x = 758;
dtext.y = 384;
var A:MovieClip = new aMC();
A.x = 225;
A.y = 275;
addChild(A);
var W:MovieClip = new wMC();
W.x = 345;
W.y = 275;
addChild(W);
var G:MovieClip = new gMC();
G.x = 470;
G.y = 275;
addChild(G);
var B:MovieClip = new bMC();
B.x = 590;
B.y = 275;
addChild(B);
var L:MovieClip = new lMC();
L.x = 715;
L.y = 275;
addChild(L);
var O:MovieClip = new oMC();
O.x = 820;
O.y = 275;
addChild(O);
var GG:MovieClip = new ggMC();
GG.x = 940;
GG.y = 275;
addChild(GG);
var dSoundReq:URLRequest = new URLRequest("
http://www.clevelandbrowns.cc/audio/dSound.mp3");
var dSound:Sound = new Sound();
var dChannel:SoundChannel = new SoundChannel();
dSound.load(dSoundReq);
D.addEventListener (MouseEvent.MOUSE_OVER, dRoll);
function dRoll (evt:MouseEvent):void {
addChild(dtext);
} // closes Index function
} // closes Index class
} // closes package

I got the problem: my tag list loaded in the whichCode dropdown by the myReadXMLPreferences function has some items beginning with numerical chars (example: 1ACDE) and they are not allowed as tags (I did not remember this limitation). If I choose an alphabetic first char code from the list the script is working.
I think I should filter the list putting a string before any numerical code.

Similar Messages

  • [svn:fx-trunk] 9932: Add ASDoc version tags to new or untagged classes - Part 2

    Revision: 9932
    Author:   [email protected]
    Date:     2009-09-02 12:17:26 -0700 (Wed, 02 Sep 2009)
    Log Message:
    Add ASDoc version tags to new or untagged classes - Part 2
    QE notes: -
    Doc notes: -
    Bugs: -
    Reviewer: -
    Tests run: - checkintests
    Is noteworthy for integration: No
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/airframework/src/spark/skins/spark/SparkChromeWindowed ApplicationSkin.mxml
        flex/sdk/trunk/frameworks/projects/airframework/src/spark/skins/spark/WindowedApplication Skin.mxml
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/RichTextEditor.mxml
        flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/Text.as
        flex/sdk/trunk/frameworks/projects/framework/src/mx/events/Request.as
        flex/sdk/trunk/frameworks/projects/framework/src/mx/skins/RectangularBorder.as
        flex/sdk/trunk/frameworks/projects/framework/src/mx/states/OverrideBase.as
        flex/sdk/trunk/frameworks/projects/rpc/src/mx/rpc/Responder.as
        flex/sdk/trunk/frameworks/projects/rpc/src/mx/rpc/remoting/Operation.as
        flex/sdk/trunk/frameworks/projects/rpc/src/mx/rpc/remoting/mxml/RemoteObject.as
        flex/sdk/trunk/frameworks/projects/rpc/src/mx/rpc/xml/IXMLSchemaInstance.as
        flex/sdk/trunk/frameworks/projects/rpc/src/mx/rpc/xml/SimpleXMLDecoder.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/RectangularDropShadow.as

    Wolf:
    Take a look at the pl/sql source for the apex_util package. There are a few more APIs related to purging cached pages.
    -- Page and Region Caching APIs, APIs for use by application developers
    procedure cache_purge_by_application (
    -- Purges all cached pages and regions for a given application.
    p_application in number);
    procedure cache_purge_by_page (
    -- Purges all cached pages and regions for a given application and page.
    -- If p_user_name is supplied, only that user's cached pages and regions
    -- will be purged.
    p_application in number,
    p_page in number,
    p_user_name in varchar2 default null);
    procedure cache_purge_stale (
    -- Deletes all cached pages and regions for the specified application
    -- that have passed their timeout. When you select to have a page or
    -- region be cached, you can specify an active time period. Once that
    -- has passed, that cache will not be used. This removes those
    -- unusable pages and regions from the cache.
    p_application in number);
    varad

  • Basic class understanding - trying to understand AS3

    I'm relatively new to AS3 and AS in general so forgive me...
    Is my understanding that there are no Abstract classes and
    you can't override or overload constructors of derived classes
    correct? Abstract classes aren't important for me but if it's
    possible I'd like to know how. But is there a way to overload
    default constructors and I'm just doing something wrong? Can we
    only override methods or can we overload them also. Work arounds
    would also be appreciated.
    Here's what I'm doing currently to make things work.
    -For a simple game I'm making, I'm not using FlexBuilder and
    don't want to for this project for specific reasons, so I'm using
    Flash and instead of using sprites and bitmaps I want to draw
    shapes in Flash and covert them into MovieClip symbols which I
    "link" for export as AS to use in my code. I want to make it a
    little modular so I can just change certain aspects of the code for
    different approaches.
    If I create a class Actor which extends MovieClip the default
    constructor has to be Actor() with no arguments. But I'd like my
    class to be able to have arguments like initial x and y
    coordinates. I know you can just create methods to initialize each
    part but I'd like to try and have a default constructor to do so.
    In Flash I notice that if you derive a written class or built
    in class it requires the standard default constructor, "which I may
    be wrong about and I hope I am and someone could show me what I'm
    doing wrong", I found if you derive a class based on a symbol you
    linked for export as AS I can create a new constructor with
    whatever argument(s) I want (so this is why I'm making this post,
    if I can do this couldn't there be a way to override
    constructors?).
    Here's how I'm doing it currently...
    1) So I create a base class called Actor which extends
    MovieClip save it as Actor.as and default constructor of Actor()
    add whatever properties I want.
    2) Then I create an object in my library, let's call it
    mcShip, then I link that symbol for export as ActionScript and have
    it's base class as Actor and name the class ShipMC.
    3) I then create a new .as file and call this one
    ShipActor.as, this class ShipActor extends ShipMC and then I create
    a default constructor ShipActor(gs:GameScreen, xA:Number,
    yA:Number) and this works fine
    (also I create a method in Actor class called ActorSuper and
    call it from ShipActor with passed in arguments, since I don't know
    of a way to overload the parent class' constructor)
    If I were to just have my mcShip with a base class of
    flash.display.MovieClip and I try to create ShipActor with the
    constructor above it says missing default constructor. The above 3
    steps is the only way I can get it to work for now. Is there a way
    to overload the constructor? If not are there any other work
    arounds?
    I'm only looking at this for object oriented approach more
    than anything. Sorry for the lengthy post but I didn't want any
    confusion, or any more confusion -.-
    Thanks for taking the time to read this post
    -John

    Your correct in that you cannot define abstract classes in
    ECMA based actionscript nor does Actionscript allow you to overload
    at all. There are work arounds for both though such as just have
    your overloaded methods use a single Object as its argument and
    that Object contain the different parameters.
    I find developing in the Flash IDE difficult at best so if
    you'd like another option besides flex builder you can use eclipse
    webtool kit with FDT. Its only got 30 days free but its worth it to
    buy it ( trust me ). A tip though is to install the latest flex sdk
    and change the source library to it so you can use Ant to build
    your swf's.
    For an object called Actor I would just extends the Sprite
    package instead of MovieClip unless you're going to manipulate its
    timeline ( why would you though ). If you need an tweening package
    check out GreenSock's TweenLite. Its better then flash's default
    one.

  • ABAP unit: test classes part of prod. code

    Hi all,
    I've read <a href="https://weblogs.sdn.sap.com/pub/u/266">Thomas Weiss</a>'s weblog: <a href="/people/thomas.weiss/blog/2004/12/17/a-spotlight-on-abap-unit-part-1 Spotlight on ABAP Unit Part 1</a>.
    I posted a question there, but apparently Thomas can't answer at the moment, and since I'm impatient for getting someone's opinion, I reckon we can discuss that topic here  :^)
    As explained in the <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/c1be1003-0701-0010-3795-f87160de6483">NetWeaver Developer’s Guide Using ABAP</a>, the test classes are part of the program under test (PUT):
    <i>In ABAP Unit, test classes are part of the production code of the TU. This avoids problems arising from the test code being separate from the production code:
    - Programs and tests must be kept synchronized.
    - You have to ensure that the test and program code are transported together.
    - External test code only enables black box tests with an outside perspective of the tested program.
    Since the test code is part of the production code, it is easy to keep the unit tests and the
    production code up to date if the latter is changed.
    Although the test code and the production code are transported through the system landscape, ABAP unit tests do not increase the load on the production system. By default, the test code is not compiled in the production system. Therefore, the test code can never be executed in the production system.</i>
    On the other hand, this idea is quite different from what suggested by other unit testing frameworks.
    For instance, the documentation of <a href="http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html">Test::Unit - Ruby Unit Testing Framework</a> reads:
    <i>It‘s handy to collect a bunch of related tests, each test represented by a method, into a common test class that knows how to run them.
    The tests will be in a separate class from the code they‘re testing for a couple of reasons. First of all, it allows your code to stay uncluttered with test code, making it easier to maintain. Second, it allows the tests to be stripped out for deployment, since they‘re really there for you, the developer, and your users don‘t need them. Third, and most importantly, it allows you to set up a common test fixture for your tests to run against.</i>
    Regarding the advantages outlined by NetWeaver Developer’s Guide:
    - Programs and tests might be kept synchronized even if they don't belong to the same unit of code.
    - Moreover, you could assure that the test and program code are transported together by saving them in the same package.
    - And quite frankly, I don't have a thourough understanding of the reason why external tests only allow <i>black box tests with an outside perspective</i>.
    What are your opinions on this?
    Regards, Davide

    Hi,
    when I started unit testing with JUnit I was quite surprised that SAP groups the tests with the production code. But now I actually really like it. It has a few advantages:
    - Good tests serve as an excellent documentation so why not bundling them together.
    - If you want to look at the tests they are easy to find.
    - I write all my class tests as local classes. I found out that it really helps me to focus on writing tests only for the class under test. Sometimes it is quite easy to forget the "unit" and write integration tests again.
    Regarding your question:
    >And quite frankly, I don't have a thourough understanding of the reason why external tests only allow black box tests with an outside perspective.
    Usually I would not use the term black box testing in this context. Maybe you mean that it is easy to access private attributes, methods when you group class and testclass together?
    Normally black box testing means that you cannot look at the implementation of the code under test. So your tests are based on the specifications or if there is not one, on your common sense.
    cheers
    Thomas

  • Basic class structure

    I've managed to create several applications in AS 3 without
    ever going face to face with packages and classes. I know that
    seems hard to believe, but anyway-- now I want to use something in
    the corelib and can't figure where I'm supposed to put these files
    I've downloaded. I know this is sub basic but would appreciate
    help.

    funonmars,
    > Hi David, Thanks for your help.
    Sure thing!
    > I tried to implement your class structure, then gave it
    a rest, then tried
    > again today to no avail. Here's a
    >
    http://henryjones.us/articles/using-the-as3-jpeg-encoder
    to the
    > JPGencoder demo that got me interested,
    Gotcha. Yes, that link helps. I ran through the tutorial
    (it's
    surprisingly quick!) and met with success. There are various
    ways it
    *could* be done -- classpath preferences are flexible -- but
    here's what I
    did.
    In the tutorial, just beneath the "First Things First"
    heading, Henry
    writes:
    "Once you have the library, just drop it into your classes
    folder and you
    are ready to go. Now we can import the JPGEncoder."
    The phrase that's open to interpretation is "your classes
    folder." For
    my development workflow, just personal preference, I keep
    third party AS2
    and AS3 classes in these folders:
    C:\Documents and Settings\<username>\My Documents\My
    Projects\ActionScript
    2.0 Classes
    C:\Documents and Settings\<username>\My Documents\My
    Projects\ActionScript
    3.0 Classes
    These corelib classes are written in AS3, so I put them into
    my
    ActionScript 3.0 Classes folder. Specifically, I visited the
    Google Code
    repository linked from Henry's site:
    http://code.google.com/p/as3corelib/.
    I downloaded corelib-.90.zip and extracted its contents to my
    desktop (this
    created a folder called corelib-.90 on my desktop). Inside
    that folder, I
    found a src subfolder. I assumed that meant "source," so I
    opened it -- and
    sure enough, there was the expected com folder. Inside that
    com folder was
    an adobe folder, and so on. The JPGEncoder class was
    ultimately in this
    folder structure: com\adobe\images\JPGEncoder.
    I already had a number of third party AS3 classes in my
    ActionScript 3.0
    Classes folder. Of those, some are located inside a root
    folder named net,
    some in edu, and some in com. My com folder already had a
    number of
    subfolders inside it, but not yet adobe; so I dragged the
    adobe folder
    (along with all of its subfolders) from the corelib-.90
    folder on my desktop
    into my ActionScript 3.0 Classes\com folder.
    From the standpoint of ActionScript 3.0 Classes, then, I had
    a
    com\adobe\images folder structure that led to the class file
    in question.
    Here's the relevant classpath setting in my Flash
    preferences:
    C:\Documents and Settings\<username>\My Documents\My
    Projects\ActionScript
    3.0 Classes
    Based on that classpath setting, here's my import statement:
    import com.adobe.images.JPGEncoder;
    I can see now, in my previous email, that I accidentally
    misled you with
    a suggestion for the wrong import path (apologies on that! I
    misread your
    folder structure). In short, the import path needs to match
    the folder
    structure of the class files themselves -- from the starting
    point of their
    parent-most (aka root) folder.
    I hope that clears it up!
    > Your book arrived today, so maybe that will help me make
    > sense of it.
    Foundation Flash CS3 for Designers is a FLA-centric book, so
    it may not
    help you especially with external class files -- but I
    certainly hope you
    get good use out of it! :) Tom and I tried to cover a broad
    range of
    topics.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Help with designing basic class

    Ok, I'm trying to learn java by implementing a Recipe program that I will eventually put up on my web page. My thought was to create a base class called recipe that would essentially be a collection of strings and such. This would then be tied to a database with getFromDatabase() methods etc... However I'm I just want to clarify a few things and make sure I'm headed in the right direction.
    I figure I should create my class something like this:
    public class Recipe
      public String recipeName;
      // more strings like serves source, etc...
      public int rating; // 1-5
      // Ingredient list
      // Category list
      public String directions;
      public Recipe(String recipeName)
      this.recipeName = recipeName;
    }The above is pretty much what I think is right with what I have so far. For the ingredients, I created a special class called ingredient that looks like:
    public class Ingredient
      public String qty;
      public String amt;
      public String desc;
      public Ingredient(String quant, String ammount, String description)
        this.qty = quant;
        this.amt = ammount;
        this.desc = description;
      public Ingredient()
        this.qty = "";
        this.amt = "";
        this.desc = "";
      public String toString()
        String tempstring = new String(this.qty + " " + this.amt + " " + this.desc);
        return tempstring;
    }Then in my recipe class I have:
    public List ingredients = Collections.synchronizedList(new LinkedList());and then I have two overloaded addIngredient methods to add an Ingredient object to this list.
    So am I on the right track? Should I not even bother with a special class just for ingredients?
    Also while I have your attention, if I were to try and get a list of recipes in the database (ie, SELECT recipename FROM recipes;) where should I put this method? Thank you for any help.
    -Chris

    You only use get() and set() methods for data you need to change, I didn't think that I had to point that out.
    The guy is obviously a beginner, there is no need to saturate him with loads of information that isn't too important to him right now; however, it is good to get him used to the get and set methods for the variables that might need changing, and keeping (most of) the variables private (or protected as the case may be).
    Please tell me how setting variables to private does not contribute to information hiding? @_@
    Because, the last time I heard, private variables can't be accessed by other classes.
    Not only that, the get() and set() methods DO hide information, mainly the inner workings of the code. Consider:
    public class Foo {
      private int x;
      public int getX() {
        return x;
      public void setX(int anInt){
        x = anInt;
    public class Bar {
      private Foo mFoo = new Foo();
      public int process(){
        int intialValue = myFoo.getX();
        return initialValue * 4;
    }And say for whatever reason the way Foo handled the way x was stored had to change:
    public class Foo {
      public String x = "0"; // x no longer an int
      public int getX() {
        return Integer.parseInt(x); // convert when needed
      public void setX(int anInt){
        x = new Integer(anInt).toString(); // convert back
    public class Bar {
      private Foo mFoo = new Foo();
      public int process(){
        int intialValue = myFoo.getX(); // none the wiser
        return initialValue * 4;
    }Note, because of the get and set methods, we didn't have to change Bar. I'd say this was a kind of data hiding, no?
    I do know a bit about what I'm saying. I may not be an expert, but what I said was on the wholecorrect, especially considering the OP is a beginner. I never claimed what I told him was the WHOLE of tight encapsulation, but it is a part of it. He doesn't need to know more than what I told him ATM.

  • XSLT European Language Support in XMLData class (part of Oracle XML kit)

    My code in JSP (with JDev) looks like this:
    <jsp:useBean id="XSLTProcesseur" class="oracle.jbo.html.databeans.XmlData" scope="request">
    <%
    String sImageBase = (String)session.getValue("ImageBase");
    XSLTProcesseur.initialize(application, session , request, response, out, "bilanmetastatique_BilanModule.MasterBilanMetView");
    XSLTProcesseur.setReleaseApplicationResources(true);
    XSLTProcesseur.setStylesheet(sImageBase + "/BilanMeMasterJSP.xsl");
    XSLTProcesseur.render();
    %>
    </jsp:useBean>
    In the xsl file, BilanMeMasterJSP.xsl, I use French characters and got error messages (exceptions) out of XMLData class.
    Running the same stylesheet with Stylus Editor from Object Design work fine! (IBM XSL Editor works too)
    Any help appreciated, thanks.
    null

    Does your stylesheet use:
    <xsl:output encoding="xxx"/>
    to specify a proper encoding for the
    characters you're trying to use?

  • Can you make the "Apply CSS Class" part of the editor bigger?

    Hi there...
    Just wondering - is it possible to make the "Apply CSS Class" editor window larger... It's TINY. (about 200px Square)
    As a result I can't see many of the classes...
    Cheers, Dave

    Hi Liam, I think i did what you said, only the changes don't appear?
    Am I missing something?
    I've cleared the browser cache & refreshed page etc - but can still see:
    Cheers, Dave

  • SetBackground and basic class and method calling stuff

    A few days ago I posted a thread about some paint problems. I was then told I was a bad programmer :P So I've read up a little on the subject. Hope this code looks better then the last (event though it's not as "complete" as the last one was).
    Now I've got a few new problems though.
    // Java Document
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Diamonds2 extends JFrame{
        public static void main(String[] args) {
            JFrame f = new JFrame("Diamonds 2");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            Container panel = new DiamondsPanel();
            f.getContentPane().add(panel, BorderLayout.CENTER);
              Container statusPanel = new DiamondsStatusPanel();
              f.getContentPane().add(statusPanel, BorderLayout.PAGE_END);
              f.setBackground(Color.black);
            f.pack();
              f.setResizable(false);
              f.setVisible(true);
              Game d2 = new Game();
              d2.game();
    class DiamondsPanel extends JPanel {
         public static int BallRadius = 16;
         public static int posx = 100;
         public static int posy = 1;
        public DiamondsPanel() {
            super();
            setOpaque(false); // we don't paint all our bits
            setLayout(new BorderLayout());
            setBorder(BorderFactory.createLineBorder(Color.black));
        public Dimension getPreferredSize() {
            Dimension panelSize = new Dimension(800, 580);
              return panelSize;
        protected void paintComponent(Graphics g) {
              super.paintComponent(g);
            Dimension size = getSize();
              // set color
             g.setColor (Color.red);
             // paint a filled colored circle
             g.fillOval (posx, posy, BallRadius, BallRadius);
         public void updateGamePanel() {
              posy--;
              repaint();
    class DiamondsStatusPanel extends JPanel {
         public DiamondsStatusPanel() {
              super();
              setOpaque(false);
              setLayout(new FlowLayout());
              setBorder(BorderFactory.createLineBorder(Color.black));
         public Dimension getPreferredSize() {
            Dimension panelSize = new Dimension(800, 20);
              return panelSize;
        protected void paintComponent(Graphics g) {
              super.paintComponent(g);
    class Game {
         public void game() {
              while(0 < 10) {
                   try {
                        Thread.sleep(10);
                   }     catch (InterruptedException e) {}
              //     System.out.println("Something is happening");
    }I can't set the background. I've tried to apply setBackground color to the constructors of each of the panel classes too but that won't work either.
    Secondly. How should I do the animation (the red circle should move) now. I knew how to do it before but with this new structure (I found in some swing tutorial) I can't figure it out. I've tried intializing a thread in the class Game since it couldn't be done (according to the compiler) in main. Also, before I could use isVisible() to run the while-loop now that didn't work either and I suppose using 0 < 10 is not a very good way to do it. I also made an update method in the DiamondsPanel class but I don't know how to call it. I understand I'm not doing this as it should be done. I also can't find any place that makes me understand how to do it :P
    Any answers will be welcomed with open arms (except mean ones xD).
    Thanks alot

    Styrisen wrote:
    I got the background to work.. really don't know what I did. It works thoughGreat
    So should the code for animating the ball be inside the DiamondsPanel class? Or where should it be?This is one of the crucial questions when developing an OOP app: what objects to create and what code goes where? I have not done animations, but I believe that there is a 2D forum here in the Sun forums. You might consider asking this over there (but if you do, please be sure to have each thread reference the other so as to avoid duplication of effort from the volunteers who help).
    How should the code look like? Should I use runnable? You're definitely going to need to use separate threads. That much I'm sure of.
    Should I make an infint loop? No.
    Should I use a timer class? Probably.
    Is it a bad idea to divide the panels into classes?Not only is it not a bad idea, it may be a good one.
    Good luck!
    Pete

  • Basic Class Question

    I'm a beginner at Java, stuck on one question...
    I'm supposed write a method, named isAlpha, that accepts a character parameter and returns true if the character is an uppercase or lowercase letter. Otherwise, it returns false.
    What's the proper way to write that?

    1- Write a class.
    2- Write the method named isAlpha with proper signature in this class.
    3- In this method body, you should use something like [url http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isLetter(char)]Character.isLetter() to do the test.
    If you have any problem(s), post the code you did.
    And allways paste your code between code tags exactly like this:
    &#91;code&#93;
    your code
    &#91;/code&#93;
    Regards

  • Basic 2-part question from a guitarist...

    I've been using GB for 2 years, and just upgraded by loading Logic Studio 9:
    Have been able to "dial up" the amp (50's R&B) and guitar selection: (Distorted Stratocaster).
    Have used the "action" to get some sound from the amp, but using the same procedure, I get ZERO sound from the Strat. file, so I have no idea how it is "supposed" to sound.(?)
    QUESTIONS: Why does the volume automatically drop to zero between certain amp selections?
    Why am I still unable to get any volume at all when I try to play Distorted Telecaster?
    Thanks, ahead of time.

    I can't answer all of your questions, but I think you may be confused about guitar related presets in Logic. There are effects presets which allow you to plug your guitar into an interface and play through those effects, and there are software instrument presets which can be played "in the box" using a MIDI keyboard or by somehow entering MIDI data into Logic. "Distorted Stratocaster" is a software instrument preset, not an effects preset. So if you're trying to play a real guitar through that, it just won't work.

  • Could you please suggest me the basic ABAP class names?

    I am trying to go to ABAP training, so l like to know the basic class name that i can take to learn ABAP. Please let me know. Thank you in advance.
    Aslam.

    Fundamentals is good, but you will also need these to really get you going.
    ABAP Objects
    http://www50.sap.com/useducation/curriculum/course.asp?rid=466&cid=60187182
    Advanced ABAP
    http://www50.sap.com/useducation/curriculum/course.asp?rid=466&cid=60208381
    Programming ABAP Reports
    http://www50.sap.com/useducation/curriculum/course.asp?rid=466&cid=60193497
    ABAP Dictionary
    http://www50.sap.com/useducation/curriculum/course.asp?rid=466&cid=60173823
    Regards,
    Rich Heilman

  • Basic Sound Class

    I'm am busy creating a simple game. I want the user to be able to play wav files while the game is running. Could someone possible point me to a very basic Class that plays wav files. Basically i want to be able to create a new instance of this class and send it the filename, and it must then play the file. Try as i might, JavaSound just confuses me.
    thanks.

    have you seen this?
    [url http://www.jsresources.org/examples/SimpleAudioPlayer.java.html]sample
    sourcecode sample / demo

  • Creating xslt dataview in a app part with visual studio for office 365 :

    Hi,
    I have a requirement for creating a app part which contains a list data view in office 365. Basically app part does not support dataview so i have started working with xslt data view inside a app part.
    I have a sharepoint hosted app which contains a list. Now i am not getting a reference or a starting point to develop xslt dataview inside my app part.
    Need help :)
    thanks in advance.
    Regards:
    Sanjay Joshi

    Hi indrajeet,
    Thank you for your code. I incorporated your code in my page. Below is my code and xslt data view web parts.
    That code works fine. But i am not able to manage the title of the collumn in data view. And reading xslt code in sharepoint 2010 designer is very typical. Please help me how can i manage below problem.
    <WebPartPages:AllowFraming ID="AllowFraming" runat="server" />
    <WebPartPages:WebPartZone runat="server" FrameType="Standard" ID="full" Title="loc:full">
    <WebPartPages:XsltListViewWebPart ID="XsltListViewWebPart2" runat="server" ListUrl="Lists/Expense" IsIncluded="True" NoDefaultStyle="TRUE" Title="Test List" PageType="PAGE_NORMALVIEW" Default="False" ViewContentTypeId="0x"><xsl>
            <xsl:stylesheet
            version="1.0"
            exclude-result-prefixes="x xsl cmswrt cbq" 
            xmlns:x="http://www.w3.org/2001/XMLSchema"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:cmswrt="http://schemas.microsoft.com/WebPart/v3/Publishing/runtime"
            xmlns:cbq="urn:schemas-microsoft-com:ContentByQueryWebPart">
            <xsl:output method="xml" indent="no" media-type="text/html" omit-xml-declaration="yes"/>
           <xsl:key name="Grouping" match="Row" use="@ExpenseType" />
          <xsl:template match="/">
              <table id="ExpenseDetail" border="1" cellpadding="1" cellspacing="1" width="100%">
                 <tr class="ms-vb">
                      <td align="left" valign="middle" width="15px">Title</td>
                      <td align="left" valign="middle" width="15px"> EmployeeID</td>
                     <td align="left" valign="middle" width="15px">Employeeloginname</td>
                      <td align="left" valign="middle" width="15px">ExpenseDescription</td>
                     <td align="left" valign="middle" width="15px">TotalExpense</td>
                      <td align="left" valign="middle" width="15px">ApprovedBy</td>
                      <td align="left" valign="middle" width="15px">IsEmployeeActive</td>
                     <td align="left" valign="middle" width="15px">ApproverComments</td>
                </tr>
                </table>
         <xsl:for-each select="/dsQueryResponse/Rows/Row[generate-id(.)=generate-id(key('Grouping',@ExpenseType))]/@ExpenseType">
          <xsl:sort />
             <table border="1" cellpadding="1" cellspacing="1" width="100%">
               Group By Expense Type : <xsl:value-of select="."/>
                <xsl:for-each select="key('Grouping', .)">
                <tr class="ms-vb">
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@Title" /></td>   
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@EmployeeID" /></td>
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@Employeeloginname" /></td>
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@ExpenseDescription" /></td>
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@TotalExpense" /></td>
                    <td align="left" valign="middle" width="15px"><xsl:value-of disable-output-escaping="yes" select="@ApprovedBy" /></td>   
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@IsEmployeeActive" /></td>
                    <td align="left" valign="middle" width="15px"><xsl:value-of select="@ApproverComments" /></td>
               </tr>
              </xsl:for-each> 
            </table>  
        </xsl:for-each>  
            </xsl:template>
    </xsl:stylesheet>
    </xsl>
    </WebPartPages:XsltListViewWebPart>
    </WebPartPages:WebPartZone>
    Please help on managing the collumn name. Not sure how to keep my xslt in the page so that dataview look good.
    Regards:
    Sanjay

  • Abstract Class & Interface

    Hi ,
    I have a fundamental doubt regarding Abstract Class & Interface!!!
    What is their real benefit...whether we implement an interface or extend an Abstract class we have to write the code for the abstract method in the concrete class.Then where the benefit remained....
    And it is said that Abstract class provide default behaviour...what is the actual meaning of that?
    Thanks & Regards
    Santosh

    In this section we will redesign our OneRowNim game to fit within a hierarchy of classes of two-player games. There are many games that characteristically involve two players: checkers, chess, tic-tac-toe, guessing games, and so forth. However, there are also many games that involve just one player: blackjack, solitaire, and others. There are also games that involve two or more players, such as many card games. Thus, our redesign of OneRowNim as part of a two-player game hierarchy will not be our last effort to design a hierarchy of game-playing classes. We will certainly redesign things as we learn new Java language constructs and as we try to extend our game library to other kinds of games.
    This case study will illustrate how we can apply inheritance and polymorphism, as well as other object-oriented design principles. The justification for revising OneRowNim at this point is to make it easier to design and develop other two-player games. As we have seen, one characteristic of class hierarchies is that more general attributes and methods are defined in top-level classes. As one proceeds down the hierarchy, the methods and attributes become more specialized. Creating a subclass is a matter of specializing a given class.
    8.6.1. Design Goals
    One of our design goals is to revise the OneRowNim game so that it fits into a hierarchy of two-player games. One way to do this is to generalize the OneRowNim game by creating a superclass that contains those attributes and methods that are common to all two-player games. The superclass will define the most general and generic elements of two-player games. All two-player games, including OneRowNim, will be defined as subclasses of this top-level superclass and will inherit and possibly override its public and protected variables and methods. Also, our top-level class will contain certain abstract methods, whose implementations will be given in OneRowNim and other subclasses.
    Generic superclass
    A second goal is to design a class hierarchy that makes it possible for computers to play the game, as well as human users. Thus, for a given two-player game, it should be possible for two humans to play each other, or for two computers to play each other, or for a human to play against a computer. This design goal will require that our design exhibit a certain amount of flexibility. As we shall see, this is a situation in which Java interfaces will come in handy.
    [Page 376]
    Another important goal is to design a two-player game hierarchy that can easily be used with a variety of different user interfaces, including command-line interfaces and GUIs. To handle this feature, we will develop Java interfaces to serve as interfaces between our two-player games and various user interfaces.
    8.6.2. Designing the TwoPlayerGame Class
    To begin revising the design of the OneRowNim game, we first need to design a top-level class, which we will call the TwoPlayerGame class. What variables and methods belong in this class? One way to answer this question is to generalize our current version of OneRowNim by moving any variables and methods that apply to all two-player games up to the TwoPlayerGame class. All subclasses of TwoPlayerGamewhich includes the OneRowNim classwould inherit these elements. Figure 8.18 shows the current design of OneRowNim.
    Figure 8.18. The current OneRowNim class.
    What variables and methods should we move up to the TwoPlayerGame class? Clearly, the class constants, PLAYER_ONE and PLAYER_TWO, apply to all two-player games. These should be moved up. On the other hand, the MAX_PICKUP and MAX_STICKS constants apply just to the OneRowNim game. They should remain in the OneRowNim class.
    The nSticks instance variable is a variable that only applies to the OneRowNim game but not to other two-player games. It should stay in the OneRowNim class. On the other hand, the onePlaysNext variable applies to all two-player games, so we will move it up to the TwoPlayerGame class.
    Because constructors are not inherited, all of the constructor methods will remain in the OneRowNim class. The instance methods, takeSticks() and getSticks(), are specific to OneRowNim, so they should remain there. However, the other methods, getPlayer(), gameOver(), getWinner(), and reportGameState(), are methods that would be useful to all two-player games. Therefore these methods should be moved up to the superclass. Of course, while these methods can be defined in the superclass, some of them can only be implemented in subclasses. For example, the reportGameState() method reports the current state of the game, so it has to be implemented in OneRowNim. Similarly, the getWinner() method defines how the winner of the game is determined, a definition that can only occur in the subclass. Every two-player game needs methods such as these. Therefore, we will define these methods as abstract methods in the superclass. The intention is that TwoPlayerGame subclasses will provide game-specific implementations for these methods.
    [Page 377]
    Constructors are not inherited
    Given these considerations, we come up with the design shown in Figure 8.19. The design shown in this figure is much more complex than the designs used in earlier chapters. However, the complexity comes from combining ideas already discussed in previous sections of this chapter, so don't be put off by it.
    Figure 8.19. TwoPlayerGame is the superclass for OneRowNim and other two-player games.
    To begin with, note that we have introduced two Java interfaces into our design in addition to the TwoPlayerGame superclass. As we will show, these interfaces lead to a more flexible design and one that can easily be extended to incorporate new two-player games. Let's take each element of this design separately.
    [Page 378]
    8.6.3. The TwoPlayerGame Superclass
    As we have stated, the purpose of the TwoPlayerGame class is to serve as the superclass for all two-player games. Therefore, it should define the variables and methods shared by two-player games.
    The PLAYER_ONE, PLAYER_TWO, and onePlaysNext variables and the getPlayer(), setPlayer(), and changePlayer() methods have been moved up from the OneRowNim class. Clearly, these variables and methods apply to all two-player games. Note that we have also added three new variables, nComputers, computer1, computer2, and their corresponding methods, getNComputers() and addComputerPlayer(). We will use these elements to give our games the capability to be played by computer programs. Because we want all of our two-player games to have this capability, we define these variables and methods in the superclass rather than in OneRowNim and subclasses of TwoPlayerGame.
    Note that the computer1 and computer2 variables are declared to be of type IPlayer. IPlayer is an interface containing a single method declaration, the makeAMove() method:
    public interface IPlayer {
    public String makeAMove(String prompt);
    Why do we use an interface here rather than some type of game-playing object? This is a good design question. Using an interface here makes our design more flexible and extensible because it frees us from having to know the names of the classes that implement the makeAMove() method. The variables computer1 and computer2 will be assigned objects that implement IPlayer via the addComputerPlayer() method.
    Game-dependent algorithms
    The algorithms used in the various implementations of makeAMove() are game-dependentthey depend on the particular game being played. It would be impossible to define a game playing object that would suffice for all two-player games. Instead, if we want an object that plays OneRowNim, we would define a OneRowNimPlayer and have it implement the IPlayer interface. Similarly, if we want an object that plays checkers, we would define a CheckersPlayer and have it implement the IPlayer interface. By using an interface here, our TwoPlayerGame hierarchy can deal with a wide range of differently named objects that play games, as long as they implement the IPlayer interface. Using the IPlayer interface adds flexibility to our game hierarchy and makes it easier to extend it to new, yet undefined, classes. We will discuss the details of how to design a game player in Section 8.6.7.
    The IPlayer interface
    Turning now to the methods defined in TwoPlayerGame, we have already seen implementations of getPlayer(), setPlayer(), and changePlayer() in the OneRowNim class. We will just move those implementations up to the superclass. The getNComputers() method is the assessor method for the nComputers variable, and its implementation is routine. The addComputerPlayer() method adds a computer player to the game. Its implementation is as follows:
    [Page 379]
    public void addComputerPlayer(IPlayer player) {
    if (nComputers == 0)
    computer2 = player;
    else if (nComputers == 1)
    computer1 = player;
    else
    return; // No more than 2 players
    ++nComputers;
    As we noted earlier, the classes that play the various TwoPlayerGames must implement the IPlayer interface. The parameter for this method is of type IPlayer. The algorithm we use checks the current value of nComputers. If it is 0, which means that this is the first IPlayer added to the game, the player is assigned to computer2. This allows the human user to be associated with PLAYERONE if this is a game between a computer and a human user.
    If nComputers equals 1, which means that we are adding a second IPlayer to the game, we assign that player to computer1. In either of these cases, we increment nComputers. Note what happens if nComputers is neither 1 nor 2. In that case, we simply return without adding the IPlayer to the game and without incrementing nComputers. This, in effect, limits the number of IPlayers to two. (A more sophisticated design would throw an exception to report an error. but we will leave that for a subsequent chapter.)
    The addComputerPlayer() method is used to initialize a game after it is first created. If this method is not called, the default assumption is that nComputers equals zero and that computer1 and computer2 are both null. Here's an example of how it could be used:
    OneRowNim nim = new OneRowNim(11); // 11 sticks
    nim.add(new NimPlayer(nim)); // 2 computer players
    nim.add(new NimPlayerBad(nim));
    Note that the NimPlayer() constructor takes a reference to the game as its argument. Clearly, our design should not assume that the names of the IPlayer objects would be known to the TwoPlayerGame superclass. This method allows the objects to be passed in at runtime. We will discuss the details of NimPlayerBad in Section 8.6.7.
    The getrules() method is a new method whose purpose is to return a string that describes the rules of the particular game. This method is implemented in the TwoPlayerGame class with the intention that it will be overridden in the various subclasses. For example, its implementation in TwoPlayerGame is:
    public String getRules() {
    return "The rules of this game are: ";
    Overriding a method
    [Page 380]
    and its redefinition in OneRowNim is:
    public String getRules() {
    return "\n*** The Rules of One Row Nim ***\n" +
    "(1) A number of sticks between 7 and " + MAX_STICKS +
    " is chosen.\n" +
    "(2) Two players alternate making moves.\n" +
    "(3) A move consists of subtracting between 1 and\n\t" +
    MAX_PICKUP +
    " sticks from the current number of sticks.\n" +
    "(4) A player who cannot leave a positive\n\t" +
    " number of sticks for the other player loses.\n";
    The idea is that each TwoPlayerGame subclass will take responsibility for specifying its own set of rules in a form that can be displayed to the user.
    You might recognize that defining geTRules() in the superclass and allowing it to be overridden in the subclasses is a form of polymorphism. It follows the design of the toString() method, which we discussed earlier. This design will allow us to use code that takes the following form:
    TwoPlayerGame game = new OneRowNim();
    System.out.println(game.getRules());
    Polymorphism
    In this example the call to getrules() is polymorphic. The dynamic-binding mechanism is used to invoke the getrules() method defined in the OneRowNim class.
    The remaining methods in TwoPlayerGame are defined abstractly. The gameOver() and getWinner() methods are both game-dependent methods. That is, the details of their implementations depend on the particular TwoPlayerGame subclass in which they are implemented.
    This is good example of how abstract methods should be used in designing a class hierarchy. We give abstract definitions in the superclass and leave the detailed implementations up to the individual subclasses. This allows the different subclasses to tailor the implementations to their particular needs, while allowing all subclasses to share a common signature for these tasks. This enables us to use polymorphism to create flexible, extensible class hierarchies.
    Figure 8.20 shows the complete implementation of the abstract TwoPlayerGame class. We have already discussed the most important details of its implementation.
    Figure 8.20. The TwoPlayerGame class
    (This item is displayed on page 381 in the print version)
    public abstract class TwoPlayerGame {
    public static final int PLAYER_ONE = 1;
    public static final int PLAYER_TWO = 2;
    protected boolean onePlaysNext = true;
    protected int nComputers = 0; // How many computers
    // Computers are IPlayers
    protected IPlayer computer1, computer2;
    public void setPlayer(int starter) {
    if (starter == PLAYER_TWO)
    onePlaysNext = false;
    else onePlaysNext = true;
    } // setPlayer()
    public int getPlayer() {
    if (onePlaysNext)
    return PLAYER_ONE;
    else return PLAYER_TWO;
    } // getPlayer()
    public void changePlayer() {
    onePlaysNext = !onePlaysNext;
    } // changePlayer()
    public int getNComputers() {
    return nComputers;
    } // getNComputers()
    public String getRules() {
    return "The rules of this game are: ";
    } // getRules()
    public void addComputerPlayer(IPlayer player) {
    if (nComputers == 0)
    computer2 = player;
    else if (nComputers == 1)
    computer1 = player;
    else
    return; // No more than 2 players
    ++nComputers;
    } // addComputerPlayer()
    public abstract boolean gameOver(); // Abstract Methods
    public abstract String getWinner();
    } // TwoPlayerGame class
    Effective Design: Abstract Methods
    Abstract methods allow you to give general definitions in the superclass and leave the implementation details to the different subclasses.
    [Page 381]
    8.6.4. The CLUIPlayableGame Interface
    We turn now to the two interfaces shown in Figure 8.19. Taken together, the purpose of these interfaces is to create a connection between any two-player game and a command-line user interface (CLUI). The interfaces provide method signatures for the methods that will implement the details of the interaction between a TwoPlayerGame and a UserInterface. Because the details of this interaction vary from game to game, it is best to leave the implementation of these methods to the games themselves.
    Note that CLUIPlayableGame extends the IGame interface. The IGame interface contains two methods that are used to define a standard form of communication between the CLUI and the game. The getGamePrompt() method defines the prompt used to signal the user for a move of some kindfor example, "How many sticks do you take (1, 2, or 3)?" And the reportGameState() method defines how the game will report its current statefor example, "There are 11 sticks remaining." CLUIPlayableGame adds the play() method to these two methods. As we will see shortly, the play() method contains the code that will control the playing of the game.
    [Page 382]
    Extending an interface
    The source code for these interfaces is very simple:
    public interface CLUIPlayableGame extends IGame {
    public abstract void play(UserInterface ui);
    public interface IGame {
    public String getGamePrompt();
    public String reportGameState();
    } // IGame
    Note that the CLUIPlayableGame interface extends the IGame interface. A CLUIPlayableGame is a game that can be played through a CLUI. The purpose of its play() method is to contain the game-dependent control loop that determines how the game is played via a user interface (UI). In pseudocode, a typical control loop for a game would look something like the following:
    Initialize the game.
    While the game is not over
    Report the current state of the game via the UI.
    Prompt the user (or the computer) to make a move via the UI.
    Get the user's move via the UI.
    Make the move.
    Change to the other player.
    The play loop sets up an interaction between the game and the UI. The UserInterface parameter allows the game to connect directly to a particular UI. To allow us to play our games through a variety of UIs, we define UserInterface as the following Java interface:
    public interface UserInterface {
    public String getUserInput();
    public void report(String s);
    public void prompt(String s);
    Any object that implements these three methods can serve as a UI for one of our TwoPlayerGames. This is another example of the flexibility of using interfaces in object-oriented design.
    To illustrate how we use UserInterface, let's attach it to our KeyboardReader class, thereby letting a KeyboardReader serve as a CLUI for TwoPlayerGames. We do this simply by implementing this interface in the KeyboardReader class, as follows:
    public class KeyboardReader implements UserInterface
    [Page 383]
    As it turns out, the three methods listed in UserInterface match three of the methods in the current version of KeyboardReader. This is no accident. The design of UserInterface was arrived at by identifying the minimal number of methods in KeyboardReader that were needed to interact with a TwoPlayerGame.
    Effective Design: Flexibility of Java Interfaces
    A Java interface provides a means of associating useful methods with a variety of different types of objects, leading to a more flexible object-oriented design.
    The benefit of defining the parameter more generally as a UserInterface instead of as a KeyboardReader is that we will eventually want to allow our games to be played via other kinds of command-line interfaces. For example, we might later define an Internet-based CLUI that could be used to play OneRowNim among users on the Internet. This kind of extensibilitythe ability to create new kinds of UIs and use them with TwoPlayerGamesis another important design feature of Java interfaces.
    Generality principle
    Effective Design: Extensibility and Java Interfaces
    Using interfaces to define useful method signatures increases the extensibility of a class hierarchy.
    As Figure 8.19 shows, OneRowNim implements the CLUIPlayableGame interface, which means it must supply implementations of all three abstract methods: play(), getGamePrompt(), and reportGameState().
    8.6.5. Object-Oriented Design: Interfaces or Abstract Classes?
    Why are these methods defined in interfaces? Couldn't we just as easily define them in the TwoPlayerGame class and use inheritance to extend them to the various game subclasses? After all, isn't the net result the same, namely, that OneRowNim must implement all three methods.
    These are very good design questions, exactly the kinds of questions one should ask when designing a class hierarchy of any sort. As we pointed out in the Animal example earlier in the chapter, you can get the same functionality from an abstract interface and an abstract superclass method. When should we put the abstract method in the superclass, and when does it belong in an interface? A very good discussion of these and related object-oriented design issues is available in Java Design, 2nd Edition, by Peter Coad and Mark Mayfield (Yourdan Press, 1999). Our discussion of these issues follows many of the guidelines suggested by Coad and Mayfield.
    Interfaces vs. abstract methods
    We have already seen that using Java interfaces increases the flexibility and extensibility of a design. Methods defined in an interface exist independently of a particular class hierarchy. By their very nature, interfaces can be attached to any class, and this makes them very flexible to use.
    Flexibility of interfaces
    Another useful guideline for answering this question is that the superclass should contain the basic common attributes and methods that define a certain type of object. It should not necessarily contain methods that define certain roles that the object plays. For example, the gameOver() and getWinner() methods are fundamental parts of the definition of a TwoPlayerGame. One cannot define a game without defining these methods. By contrast, methods such as play(), getGamePrompt(), and reportGameState() are important for playing the game but they do not contribute in the same way to the game's definition. Thus these methods are best put into an interface. Therefore, one important design guideline is:
    [Page 384]
    Effective Design: Abstract Methods
    Methods defined abstractly in a superclass should contribute in a fundamental way to the basic definition of that type of object, not merely to one of its roles or its functionality.
    8.6.6. The Revised OneRowNim Class
    Figure 8.21 provides a listing of the revised OneRowNim class, one that fits into the TwoPlayerGame class hierarchy. Our discussion in this section will focus on the features of the game that are new or revised.
    Figure 8.21. The revised OneRowNim class, Part I.
    (This item is displayed on page 385 in the print version)
    public class OneRowNim extends TwoPlayerGame implements CLUIPlayableGame {
    public static final int MAX_PICKUP = 3;
    public static final int MAX_STICKS = 11;
    private int nSticks = MAX_STICKS;
    public OneRowNim() { } // Constructors
    public OneRowNim(int sticks) {
    nSticks = sticks;
    } // OneRowNim()
    public OneRowNim(int sticks, int starter) {
    nSticks = sticks;
    setPlayer(starter);
    } // OneRowNim()
    public boolean takeSticks(int num) {
    if (num < 1 || num > MAX_PICKUP || num > nSticks)
    return false; // Error
    else // Valid move
    { nSticks = nSticks - num;
    return true;
    } // else
    } // takeSticks()
    public int getSticks() {
    return nSticks;
    } // getSticks()
    public String getRules() {
    return "\n*** The Rules of One Row Nim ***\n" +
    "(1) A number of sticks between 7 and " + MAX_STICKS +
    " is chosen.\n" +
    "(2) Two players alternate making moves.\n" +
    "(3) A move consists of subtracting between 1 and\n\t" +
    MAX_PICKUP + " sticks from the current number of sticks.\n" +
    "(4) A player who cannot leave a positive\n\t" +
    " number of sticks for the other player loses.\n";
    } // getRules()
    public boolean gameOver() {   /*** From TwoPlayerGame */
    return (nSticks <= 0);
    } // gameOver()
    public String getWinner() {        /*** From TwoPlayerGame */
    if (gameOver()) //{
    return "" + getPlayer() + " Nice game.";
    return "The game is not over yet."; // Game is not over
    } // getWinner()
    The gameOver() and getWinner() methods, which are nowinherited from the TwoPlayerGame superclass, are virtually the same as in the previous version. One small change is that getWinner() now returns a String instead of an int. This makes the method more generally useful as a way of identifying the winner for all TwoPlayerGames.
    Similarly, the getGamePrompt() and reportGameState() methods merely encapsulate functionality that was present in the earlier version of the game. In our earlier version the prompts to the user were generated directly by the main program. By encapsulating this information in an inherited method, we make it more generally useful to all TwoPlayerGames.
    Inheritance and generality
    The major change to OneRowNim comes in the play() method, which controls the playing of OneRowNim (Fig. 8.22). Because this version of the game incorporates computer players, the play loop is a bit more complex than in earlier versions of the game. The basic idea is still the same: The method loops until the game is over. On each iteration of the loop, one or the other of the two players, PLAYER_ONE or PLAYER_TWO, takes a turn making a movethat is, deciding how many sticks to pick up. If the move is a legal move, then it becomes the other player's turn.
    Figure 8.22. The revised OneRowNim class, Part II.
    (This item is displayed on page 386 in the print version)
    /** From CLUIPlayableGame */
    public String getGamePrompt() {
    return "\nYou can pick up between 1 and " +
    Math.min(MAX_PICKUP,nSticks) + " : ";
    } // getGamePrompt()
    public String reportGameState() {
    if (!gameOver())
    return ("\nSticks left: " + getSticks() +
    " Who's turn: Player " + getPlayer());
    else
    return ("\nSticks left: " + getSticks() +
    " Game over! Winner is Player " + getWinner() +"\n");
    } // reportGameState()
    public void play(UserInterface ui) { // From CLUIPlayableGame interface
    int sticks = 0;
    ui.report(getRules());
    if (computer1 != null)
    ui.report("\nPlayer 1 is a " + computer1.toString());
    if (computer2 != null)
    ui.report("\nPlayer 2 is a " + computer2.toString());
    while(!gameOver()) {
    IPlayer computer = null; // Assume no computers
    ui.report(reportGameState());
    switch(getPlayer()) {
    case PLAYER_ONE: // Player 1's turn
    computer = computer1;
    break;
    case PLAYER_TWO: // Player 2's turn
    computer = computer2;
    break;
    } // cases
    if (computer != null) {                           // If computer's turn
    sticks = Integer.parseInt(computer.makeAMove(""));
    ui.report(computer.toString() + " takes " + sticks + " sticks.\n");
    } else {                                          // otherwise, user's turn
    ui.prompt(getGamePrompt());
    sticks =
    Integer.parseInt(ui.getUserInput()); // Get user's move
    if (takeSticks(sticks)) // If a legal move
    changePlayer();
    } // while
    ui.report(reportGameState()); // The game is now over
    } // play()
    } // OneRowNim class
    Let's look now at how the code decides whether it is a computer's turn to move or a human player's turn. Note that at the beginning of the while loop, it sets the computer variable to null. It then assigns computer a value of either computer1 or computer2, depending on whose turn it is. But recall that one or both of these variables may be null, depending on how many computers are playing the game. If there are no computers playing the game, then both variables will be null. If only one computer is playing, then computer1 will be null. This is determined during initialization of the game, when the addComputerPlayer() is called. (See above.)
    In the code following the switch statement, if computer is not null, then we call computer.makeAMove(). As we know, the makeAMove() method is part of the IPlayer interface. The makeAMove() method takes a String parameter that is meant to serve as a prompt, and returns a String that is meant to represent the IPlayer's move:
    public interface IPlayer {
    public String makeAMove(String prompt);
    [Page 385]
    In OneRowNim the "move" is an integer, representing the number of sticks the player picks. Therefore, in play() OneRowNim has to convert the String into an int, which represents the number of sticks the IPlayer picks up.
    On the other hand, if computer is null, this means that it is a human user's turn to play. In this case, play() calls ui.getUserInput(), employing the user interface to input a value from the keyboard. The user's input must also be converted from String to int. Once the value of sticks is set, either from the user or from the IPlayer, the play() method calls takeSticks(). If the move is legal, then it changes whose turn it is, and the loop repeats.
    [Page 386]
    There are a couple of important points about the design of the play() method. First, the play() method has to know what to do with the input it receives from the user or the IPlayer. This is game-dependent knowledge. The user is inputting the number of sticks to take in OneRowNim. For a tic-tac-toe game, the "move" might represent a square on the tic-tac-toe board. This suggests that play() is a method that should be implemented in OneRowNim, as it is here, because OneRowNim encapsulates the knowledge of how to play the One-Row Nim game.
    Encapsulation of game-dependent knowledge
    [Page                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

Maybe you are looking for

  • DIP can't contact OID after OIM domain extension and configuration

    Hello, After extending our domain for OIM, configuring and propagating the domain, we are having issues with DIP contacting OID. When starting the managed server, wls_ods1, the following error is reported in the .out file: <Error> <oracle.dip> <DIP-1

  • Can't install oracle 10g on windows 2008 R2

    Please help me I want install oracle 10g on windows 2008 R2 but can't install because I don't have file install oracle_10.2.0.4 and i can't download file from oracle.com and oracle 11g i not license Where can download file oracle install 10.2.0.4 tha

  • How to configure the share document option

    After installing, testing and de-installing Sparrow Mail I am not able to share a document thru the Share Via Mail command. Nothing happens after selecting Pages, Word or PDF. How can I reconfigure iWork to put the file in a Mail message? What if I u

  • Read Only/ Plan Mode Changes for a layout with two different queries

    Hi, I have a situvation where a layout opens in a read only mode and when the users click on button plan, it changes to plan mode. The catch here however is the queries for read mode and plan mode are slightly different, in the read only mode the que

  • Split large AVCHD file

    Hi, A friend used my Handycam to record another friends gig. It was recorded in one shot, lasting about 50mins, and is about 19gbs in size when imported into Final Cut Express. I'm now trying to chop it up into the 6 individual songs, but I think the