Small tennis simulation in Java

Hello, I am a new programmer and I have Several questions about how to implement object oriented features in my tennis simulation being written in Java. http://telis.edugraf.ufsc.br/apliques/2007/2/ProjetoTenis/src
(Just cut and paste it to see the source code for my simulator)
First I will tell how my simulation works so that you all can understand better what I need to do, how to do it and especially how to do it in an object oriented way (can have some generic programming too)
This is how the program works
I am doing a little tennis program in which I implement the simulation of a game of a tennis match based on random number generation and probabilities. For example, it chooses a number between 1 to 2, and if the result is 1, the player hits the first serve. If not, then the second one.
Then, when he hits any of the two serves, it sorts a number between 1 to 10. In the first serve case, if the number is anything between 1 to 8, the server wins the point. In the second serve case, the server wins the point if the value choosed is anything between 1 to 5.
I have three big classes, one that has the main method and creates an object that represents a tennis match.
This object calls for a method of the class "Game", the class responsible for 'managing' a game from a tennis match.
For now the only thing this "Game" class is doing, is holding the method responsable for controlling the serves, that as was said in the above paragrapher, are the responsables for deciding who is going to win a point. The method "saque" (serve in english) chooses a serve and then send it to a certain method of the "Pontos" (points) class to select who winned the point.This class contains three methods, each one for one of the three possibilities: first serve in, second serve in and double fault. When the winner of the point is choosed, I would like it to return the two variables that represent the points that each player will have after the point is finished,
back to method "saque" (serve) of the Game class.
This brings me to the first problem: methods cannot return two values. So, can I create an object composed of two fields and return it? If I can, can you guys show how to do it?. If not, what you suggest?. I need to return them because I intend to create in the "Game" class, another method, one that will control the game, or in another words, finish the program when a player collects enough points to win the game.
Then in the "game" class, I would like to send these two values, whether they will be in an object or in another form to the "control" method that I intend to create in the same class. This brings to the second question which is: when these points will be returned, should I create this "control method" in the same class and send the values to it, or should I do something completely different to allow bigger modularization?.
And the last question comes to the surface due to the fact that the point count changes during the game. The way it is now. at each new point 15points will be given to the variable that represents the score of one of the players.
How should I change this value according to occasion? Should I create an object of the type "Point" to do this?
Thanks for all the suggestions and recomendations.
Edited by: ratzenberguer on Dec 1, 2007 4:06 PM
Edited by: ratzenberguer on Dec 1, 2007 4:07 PM

This brings me to the first problem: methods cannot return two values. So, can I create an object composed of two fields and return it?
Yes. Exactly... If you really must!
But a method should return one and only value and have no (or limited and predictable) side effects.
So for instance a getter (ie getAttribute() method) should NOT update the attribute in the GUI (for instance) as a side effect. But a getAverage() method might reasonably cache (store) the calculated average.
The usual approach is:
* perform some operation which stores values in class attributes
* retrieve those class attributes via getters.
for example:
studentGrades.calculateAverage();
studentGrades.getAverage();
studentGrades.getSum();
studentGrades.getCount();
If a method really must return several values, and it is only used internally (within one class) then it's best to return an "inner class" (google that). I do this fairly routinely in swing apps... for inter-thread communication. I recommend making the attributes public and final.
If a method is used externally (between classes) then I personally will create a package level class to return the value... but only if I must.
If the method is public then I personally won't create a public class just to return multiple values from a method... coz this is a poor public API, coz it's difficult to figure out how to use it properly.
Obviously, If the method returns a class which is allready part of the public API then that's ok... For example: TennisPlayerBuilder.getPlayer() might return a configured TennisPlayer... coz TennisPlayer is part of the public API.
Clear as mud right?
Jeez I hope someone else can explain this properly... On rereading this, I'm a mess.

Similar Messages

  • Need help in designing an  ATM simulation in java

    Hi,
    I've got to design a simulation of an ATM in java(client/server) and if anyone can help me with some coding, it would be nice :)
    I've got to design the interface on the client side and connect it to a database on a remote server. Any codings of an ATM program will be of great help to me. so please give me a little help.. I'm really stuck and it's the first time I'm doing programming in Java.
    Regards
    Roubin.

    go to google.com and type in "ATM simulation in java." There are a number of example of this type of project.

  • JAXB 1: is it possible to go from enum simulation in Java to XML Schema?

    I know how to get an enum simulation in java from XML schema, but can it be done in the other direction, in the context of a web service implementation?
    The thing is from schema to java a customization file is used. But there's no specification for such a customization file usability when going from java to schema. So far, i'm getting a string for enum wrapper.

    Well, i got it to work in JAXB 1, w/o xfire, schema-to-java. Marshall and unmarshall.
    But w/ xfire, it doesn't appear to be possible. Would probably require implementing it for them myself...

  • How to create a discrete event Simulator in java

    I want to create a discrete event simulator in java to communicate between 1000 hots on the same machine.Can anyone help me with that???

    So I figured out how to create one, but when I try to do personProfile.save(), its always coming back as false. Any ideas why this might be?

  • Simulation in java

    hello:
    i am working on a project which deliver a signal from sensor and send it to computer by serial port.
    actually i need to make simulation to this system using Java, i mean that i want to exchange the hardware part (sensor) and simulate it in java, so can java do that? and how?
    note: my sysetm should count people who cut the sensor beam.

    If I were doing this I would make my communication with the hardware as an implementation of some interface so that I would then have two implementations of that interface. An implementation that talks to the hardware and one that is a simulator.
    For example
    import java.util.*;
    interface HardwareCommunicationsIF
        void addEventListener(HardwareEventListener eventListener);
    interface HardwareEventListener
        void notifyEvent(HardwareEvent hardwareEvent);
    class HardwareEvent
        // place in here stuff to identify the event type and parameters associated with the event
        public Date getEventTime()
            return eventTime;
        private Date eventTime = new Date();
    abstract class AbstractCommunications implements HardwareCommunicationsIF
        public void addEventListener(HardwareEventListener eventListener)
            if (eventListener != null)
                listeners.add(eventListener);
        protected void notifyListeners(HardwareEvent event)
            for (HardwareEventListener listener : listeners)
                listener.notifyEvent(event);
        private List<HardwareEventListener> listeners = new ArrayList<HardwareEventListener>();
    class RealHardwareCommunications extends AbstractCommunications
        // In here you talk to the hardware and then notify the listeners using
        // the notifyListeners() method.
        RealHardwareCommunications()
            // Setup the communications with the hardware
            // and start a thread that processes the information from
            // the real hardware.
    class DummyHardwareCommunications extends AbstractCommunications
        // In here you run a thread which generates dummy events
        // then you notify the listeners using
        // the notifyListeners() method. For example
        public DummyHardwareCommunications()
            new Thread(new Runnable()
                public void run()
                    Random random = new Random();
                    while (true)
                        // a random delay before generating the next event
                        int delta = random.nextInt(1900) + 100;
                        synchronized (this)
                            try
                                wait(delta);
                            catch(Exception e)
                                // Nothing to do
                        HardwareEvent event = new HardwareEvent();
                        notifyListeners(event);
            }).start();
    public class Fred114
        public static void main(String[] args) throws Exception
            // You could use Class.forName() to define whether or not
            // you use the real or dummy comms.
            //HardwareCommunicationsIF comms = new RealHardwareCommunications();
            HardwareCommunicationsIF comms = new DummyHardwareCommunications();
            comms.addEventListener(new HardwareEventListener()
                public void notifyEvent(HardwareEvent hardwareEvent)
                    System.out.println("Event received at " + hardwareEvent.getEventTime());
    }

  • Simulator for java card

    hi
    i am new to java card technology...i am writing the applets in netbeans using java card plugin....the problem is i m not able to simulate the applet..it is showing build successfully, but wen i run the app it is showing nothing.....so can anyone suggest me a suitable simulator for the same....

    Hi,
    I assume you are after details on how to use the simulators? There are examples and documentation with the JC specifications and developer kit. Both of these are available from the Sun website [http://java.sun.com/javacard/].
    If you are after details on how to develop your own, the JC specifications outline the requirements for the JCRE and JCVM that you can use to implement a simulator.
    Cheers,
    Shane

  • Need suggestion regarding simulation of Java Card using a floppy

    Hi All,
    I am working on a project wherein I have to simulate a Java Card application using a floppy. I am writing my own Card Terminal and CardTerminalFactory. Thats what I have started working on. Will that serve the purpose or do I have to think about some other approach like just overriding the cardInserted method of CTListener class? I want to achieve communication between the host application and the floppy(which is my java card) Please advise.
    I would like to thank DurangoVa and Nilesh for helping me out sorting out the error in running the converter.
    Thanks in advance

    Are you referring to a Floppy diskette drive ?

  • Problem with too small page size using Java 2D Printing API.

    Hello,
    I have problem with resolution of printer using Java 2D Printing API. Despite my printer has 600 x 600 DPI, inside java.awt.print.Printable.print(Graphics, PageFormat, int) I receive page format with 600 x 840 page size.
    I have tried to set resolution using javax.print.attribute.PrintRequestAttributeSetand javax.print.attribute.standard.PrinterResolution, but with no result.
    Can anybody solve this problem?
    Regards,
    Karl.

    600 x 840 is a Point value; Point is defined as 1/72nd of an inch. Printers do have much higher DPI than this, but I believe that this DPI has to do with richness of the printed image, not an actual ability to color with that level of resolution. You might want to try calling zoom on your Graphics2D object. Otherwise, I don't know what else you can try.

  • Google map simulation in java

    Hi guys, i want to simulate my own version of google map but would like to design it in such a way that the geographical data is kept separate from the actual implementation functionality e.g use the data for different areas instead of me rewriting the code. Now, i have been searching the web and have noticed that java has a Class GeoData (http://flickrj.sourceforge.net/api/com/aetrion/flickr/photos/GeoData.html) which can be used to create the long/latitude but what i would like to know is are there any tutorials available that one could recommend me to show how to use this class? As again, i idealy would like to keep these components separate.
    Your input would be so greatful guys.
    Thanks

    Oh i see cool. I've been browsing the net have found this link http://geotools.codehaus.org/ which seems to be what looks like some sort of IDE for map creation. Has anybody here ever used this before and what are you thought about this?
    Edited by: nvidia1 on May 20, 2008 12:31 PM

  • Keyboard simulation in Java

    Hello
    How can I simulate a keystroke like Alt+Shift through java code?
    Thanks,
    Tomer

    Hi,
    :. I don't know what exactly you intend to accomplish. But, I have used the following code in order to simulate keys pressing inside a Java application.
          /* - - - Simulates TAB (java.awt.Event)
          EventQueue evtq = Toolkit.getDefaultToolkit().getSystemEventQueue();
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_PRESSED,
                          0, 0, KeyEvent.VK_TAB, KeyEvent.CHAR_UNDEFINED) );
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_RELEASED,
                          0, 0, KeyEvent.VK_TAB, KeyEvent.CHAR_UNDEFINED) );
          /* - - - Simulates Shift+TAB (java.awt.Event)
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_PRESSED, 0,
                          InputEvent.SHIFT_DOWN_MASK, KeyEvent.VK_TAB,
                          KeyEvent.CHAR_UNDEFINED) );
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_RELEASED, 0,
                          InputEvent.SHIFT_DOWN_MASK, KeyEvent.VK_TAB,
                          KeyEvent.CHAR_UNDEFINED) );:. However, as far as I know to send keys to the whole OS you have to create a 'Hook' as described inside Win32API documentation. That's for Microsoft Windows naturaly.
    Cheers.
    Roque

  • How to Return ten records into java class by using oracle stored procedure

    Hello sir/Friends
    There is a procedure that returns 10 records from the oracle table and i want to display all 10 records into the table in java class.
    Please reply
    Thanking you.

    When you execute the stored procedure it will return your results as a ResultSet. Iterate over itto get the values you need then do with them as you please.
            List<MyObject> results = new ArrayList<MyObject>();
            MyObject mo = null;
            ResultSet rs = stmt.executeQuery("SELECT a_value FROM a_table");
            while (rs.next())
                mo = new MyObject();
                mo.setValue(rs.getString(1));
                results.add(mo);
            }

  • Beginner's Question on simulation of java card application

    Hi,
    I am trying to run a basic Java card application.
    To simulate the java card application, I created jcwde.app and tried C:\>jcwde -p 9025 jcwde.app
    I got and exception like:
    Exception in thread "main" java.lang.UnsatisfiedLinkError: markHeap
    at com.sun.javacard.impl.NativeMethods.markHeap(Native Method)
    at javacard.framework.Dispatcher.cardInit(Dispatcher.java:188)
    at javacard.framework.Dispatcher.main(Dispatcher.java:63)
    at javacard.framework.JCWDEDispatcher.main(JCWDEDispatcher.java:28)
    at com.sun.javacard.jcwde.Main.run(Main.java:85)
    at com.sun.javacard.jcwde.Main.main(Main.java:148)
    Can anyone help me to find out the reason for this exception?
    The content of jcwde.app is
    // applet AID
    com.sun.javacard.installer.InstallerApplet 0xa0:0x0:0x0:0x0:0x62:0x3:0x1:0x8:0x1
    wallet.Wallet
    Thanx in advance.
    anju

    I see terms like ...
    Core Java: The main libraries.
    JDK: (J)ava (D)evelopement (K)it) - AKA: (S)oftware (D)evelopement (K)it although the terms are not exactly synonomous
    J2EE:(J)ava 2 (E)nterprise (E)dition (builds on the J2SE with additional librarities for true business application building)
    J2SE: (J)ava 2 (S)tandard (E)dition (The core libraries for general Java program developement, w/o the extra stuff that is in the J2EE
    Go to java.sun.com and check out the tutorials, the readme files that come with the downloads, the release notes, etc ... HTH

  • Java card simulator and WTK communication problem.

    Hi ,
    I am a newbie to java card .I am doing project on java card based sim.
    For that I am using JavaCard SDK 2.2.2 and WTK 2.5.2 .
    Now when i am trying to connect to cref(java card simulator) from java card midlet,I am getting protocol mismatch error.This is because of WTK runs on slot T=0 and cref runs on T=1.
    then i tried with jcdk3.0.1 classic edition.It provides cref configured to run on both slots T=0 and T=1.
    But when I tried to deploy jcrmi applet on cref running on T=0 i am getting the same error "Protocol mismatch error".
    Can anybody please tell, if there is any way to configure cref to run with T=0?
    Please reply ASAP, as i am stucked with the problem from more than a month.
    Thanks in advance,
    Saviy

    Thanks Anki for replying.
    I am trying to run RMISample from development kit.With steps given in guide as follows
    1.cref -o demoee
    2.Navigate to the
    JC_CLASSIC_HOME\samples\classic_applets\RMIPurse\applet
    directory.
    3.ant all
    it works fine but when i do it with following steps:
    1.cref -o -t0 demoee
    2.Navigate to the
    JC_CLASSIC_HOME\samples\classic_applets\RMIPurse\applet
    directory.
    3.ant all
    i am getting protocol mismatch error.

  • Max number of threads in Java?

    Hi,
    I am running into a bug now that I am testing my working code. Basically, my program creates a bunch of objects that talk to each other. Each object is a thread, and at a given time (there is a one object that keeps track of time) a thread may choose to message another thread. My problem is that when I create more objects, my code doesn't run to completion. For example, when I have 10 objects talking to each other, things work fine. But if I have 15, they all run for a little bit, then the program seems to just hang and not do anything.
    Is there a limit as to how many threads I can have? If I was out of memory or something, I'd get an exception, right? But I don't get anything - it just seems like things "freeze up".

    15 threads? shouldn't be a problem.
    I think th emax threads allows runs in thousands..if not ten of thousands.Java process threads itself use about 600 or more threads. howevr, it could also be the underlying system restr8iction on the number of threads allow per process????
    for you case: it's highly likely you run into the max # of threads.
    I can only think of two reasons for your application to freeze:
    1. Deadlock
    if you have an object that is synchronized..than you might have run into a deadlock (race-condition)
    for example:
    Object A has the key for Object X , and waiting for Object Z
    Object B has the key for Object Z, and waiting for Object X
    as you can see..they will never gives up the lock....so you're in a dead lock.
    2. Low memory resource. (Memory - Paging and Thrashing)
    Each of your thread is using up the resouces (memory) and processing power.
    When you reach the max or near max and needs to create more memory..the garbage collector kick in
    and try to reclaim some unused memory. This can slow down your application dramatically if the garbage
    collector is invoke often.
    Also..paging is performed when you reach max memory..the operating system keep on paging your memory (usually happens when there's a lot of threads and not enough memory. If this happen..than it
    can cause your program to becomes freeze like....remeber..each thread is given a small amount of time to
    perform a task..if the time it takes to load a page for a thread is almost equals to context switch time..than
    no work is really done..and your program "freeze"
    solution..redesign you app to prevent thrashing.
    it is likely paging is the culprit..but i would not dismiss deadlock issues.

  • Is database Engine necessary or should I use one in my Java application?

    I am writing a program which similar to a telephone directory kind of application. I have a database and I am thinking to use JDBC with mySQL for the database.
    My question is that later when this program is ready and I am going to burn it to CD, what will be happen with mySQL? Can I add mySQL (or a similar program)?
    Is it not better to make a database by Java objects or arrays within Java? What is the smart way to this when it comes to a program which in the background you have database??? Thank you for sharing your expertise...

    I am writing a program which similar to a telephone
    directory kind of application. I have a database and
    I am thinking to use JDBC with mySQL for the
    database.
    My question is that later when this program is ready
    and I am going to burn it to CD, what will be happen
    with mySQL? Can I add mySQL (or a similar program)?You can, but will users want that? Are you better off allowing users to work with any relational database they wish?
    >
    Is it not better to make a database by Java objects
    or arrays within Java? Unless you plan on writing a relational database and SQL engine on your own, the best bet is to get a real relational database.
    Hypersonic SQL is small and embeddable in Java. Cloudscape might be good, too. Derby is going to be part of Java 6, unfortunately. PostgreSQL is a terrific relational database that's free.
    What is the smart way to this
    when it comes to a program which in the background
    you have database??? Thank you for sharing your
    expertise...The smart thing is to get a real relational database and forget about doing it yourself. Databases are far more complex than a few arrays or objects.
    %

Maybe you are looking for

  • Material Master Archiving

    Hi I want to archive Materials set for deletion flag. My Main problem with Technical settings for file path, logical file. Please guide me how to customize the technical settings in SARA transaction. Sridhar

  • Getting Page not found while trying to read ws-addressing.xsd file in IE

    Hi All, Here I am creating dynamic partner link to call OSB service in my BPEL process. I wan make it dynamic to change run time server address and port numbers. Here I am getting Error (Error occurred reading inline schemas) while creating reference

  • Error "Personalization not activated." when trying to set personal

    Hi Everyone, Was wondering if anyone has encountered this situation. I have a crystal report reporting off of sap bw using bw mdx driver which I view through an iview in SAP portal. When I select the parameter values for a parameter using the picklis

  • A question about Serializable

    Hi, I have a simple question. What is the functions of Serializable interface and why we need using it in our program. Some examples are welcome. Thanks vq

  • 10.1.3r3 Diagrammer bug

    JDev team, A bug in the 10.1.3r3 diagrammer. Follow these steps: Create a new application workspace based on web [default] technology. In the model project invoke the Business Components from Tables wizard. Select any table in your favourite schema,