Open Side Menu Go to the Top

04-05-2009 , 11:05 AM
made this program this morning while acquainting myself with java swing. not sure if there is a program already like it but w/e.
Basically if you're in a spot that you want to call or bet say 33% of the time or half etc... you type it in and see if it's that time or not. This way you're not guessing how often you're doing something.
You can also test the algorithm in case you're wondering if it's random enough.

Green background means to do whatever you wanted to do that % of time
Red background means don't do it.
You'll have to figure out how to use it and what spots, I don't have the answers for that.

you can download it here and just run the jar if you have java installed
http://www.mediafire.com/?we2gyyh30gm

if you don't have java
http://www.java.com/en/download/index.jsp

screenshot (yeah pretty basic )



comments or suggestions welcome
Code:
package Randomizer;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.*;
import java.util.Random;
import javax.swing.JTextArea;
public class Randomizer extends JPanel implements ActionListener {
    private JButton goButton = new JButton("Balance");
    private JButton resetButton = new JButton("Reset");
    private JButton testButton = new JButton("Test");
    private JTextField balance = new JTextField(2);
    private JTextArea ta = new JTextArea(3, 10);



    public Randomizer() {
        add(resetButton);
        add(goButton);
        add(balance);
        add(testButton);
        add(ta);
        balance.setText("0");
        goButton.addActionListener(this);
        resetButton.addActionListener(this);
        testButton.addActionListener(this);
  }
    public void actionPerformed(ActionEvent evt) {
        int entry = 0;
        Object source = evt.getSource();
        Color color = getBackground();
        if (source == resetButton){
            color = Color.white;
            balance.setText("0");
            ta.setText("");
        }
        else if (source == goButton){
            entry = getter();
            int random = rando();
            if (random < entry){
                color = Color.green;
                ta.setText("Go Go Go!");
            }else if (random >= entry){
                color = Color.red;
                ta.setText("No No No!");

            }
        }
        else if (source==testButton)
            tester();


        setBackground(color);
        repaint();
    }
    public int getter(){
        int e = 0;
        try {
            e = Integer.parseInt(balance.getText());
            }catch  ( NullPointerException npe )   {    e = 0;}
             catch  ( NumberFormatException nfe )   {   e = 0; }
        return e;
    }

    public void tester(){
        ta.setText("");
        int pos = 0; int neg = 0;
        int testEntry = getter();
        for (int i = 0;i<100000;i++){
            int testRand = rando();
            if (testRand < testEntry)
                pos++;
            else if (testRand >= testEntry)
                neg++;
        }
       ta.append("Testing 100000 simulations\n");
       ta.append("There were " + pos + " positives\n");
       ta.append("There were " + neg + " negatives\n");

    }



    public static int rando(){
        int hi = 99; int lo = 0;
        Random rn = new Random();
        int n = hi - lo + 1;
        int i = rn.nextInt() % n;
        if (i < 0)
            i = -i;
        return lo + i;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Range Balancer by jwc529");
        frame.setSize(275, 125);
        frame.addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(new Randomizer());
    frame.show();
  }
}
Range Balance Software (java) Quote
Range Balance Software (java)
150% up to $2,000 Welcome Bonus on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Range Balance Software (java)
04-05-2009 , 11:35 AM
Looks OK to me, but one thing you should be very careful of is doing this:
Code:
int i = rn.nextInt() % n;
A lot of random number generators will produce output with very obvious "patterns" in if you do this (you can see them if you write an applet similar to this person's: see here). I don't think it'll really have that much effect for this, but for some things (like scientific experiments) it can cause big problems.

To avoid the problems with modulus/low-order bits then take the high-order bits instead with code like this:
Code:
int i = rn.nextInt() / ((RAND_MAX/n)+1);
where RAND_MAX is the largest integer that can be returned from nextInt() (probably 2^31-1=2147483647, but it's been along time since I used Java so best check).

Juk
Range Balance Software (java) Quote
04-06-2009 , 02:36 PM
The OP's code is badly violating Swing rules by performing things that should be performed on the EDT in a non-EDT thread, but I'll answer to that in another post.


Quote:
Originally Posted by jukofyork
Looks OK to me, but one thing you should be very careful of is doing this:
Code:
int i = rn.nextInt() % n;
There's no need to use the convoluted solution you're suggesting.

Java has actually a nextInt(int n) method that does what you suggest and it does it better than what you'd achieve if you were to reinvent the wheel.

I suggest the OP to simply use

Code:
int i = rn.nextInt(n)
Simple, elegant.

/**
* Returns a pseudorandom, uniformly distributed <tt>int</tt> value
* between 0 (inclusive) and the specified value (exclusive), drawn from
* this random number generator's sequence. The general contract of
* <tt>nextInt</tt> is that one <tt>int</tt> value in the specified range
* is pseudorandomly generated and returned. All <tt>n</tt> possible
* <tt>int</tt> values are produced with (approximately) equal
* probability. The method <tt>nextInt(int n)</tt> is implemented by
* class <tt>Random</tt> as follows:
* <blockquote><pre>
* public int nextInt(int n) {
* if (n<=0)
* throw new IllegalArgumentException("n must be positive");
*
* if ((n & -n) == n) // i.e., n is a power of 2
* return (int)((n * (long)next(31)) >> 31);
*
* int bits, val;
* do {
* bits = next(31);
* val = bits % n;
* } while(bits - val + (n-1) < 0);
* return val;
* }
* </pre></blockquote>
* <p>
* The hedge "approximately" is used in the foregoing description only
* because the next method is only approximately an unbiased source of
* independently chosen bits. If it were a perfect source of randomly
* chosen bits, then the algorithm shown would choose <tt>int</tt>
* values from the stated range with perfect uniformity.
* <p>
* The algorithm is slightly tricky. It rejects values that would result
* in an uneven distribution (due to the fact that 2^31 is not divisible
* by n). The probability of a value being rejected depends on n. The
* worst case is n=2^30+1, for which the probability of a reject is 1/2,
* and the expected number of iterations before the loop terminates is 2.
* <p>
* The algorithm treats the case where n is a power of two specially: it
* returns the correct number of high-order bits from the underlying
* pseudo-random number generator. In the absence of special treatment,
* the correct number of <i>low-order</i> bits would be returned. Linear
* congruential pseudo-random number generators such as the one
* implemented by this class are known to have short periods in the
* sequence of values of their low-order bits. Thus, this special case
* greatly increases the length of the sequence of values returned by
* successive calls to this method if n is a small power of two.
*
* @param n the bound on the random number to be returned. Must be
* positive.
* @return a pseudorandom, uniformly distributed <tt>int</tt>
* value between 0 (inclusive) and n (exclusive).
Range Balance Software (java) Quote
04-06-2009 , 02:59 PM
Quote:
Originally Posted by jwc529
made this program this morning while acquainting myself with java swing. not sure if there is a program already like it but w/e.
Hi, it's very good for a first Swing program.

However Swing is very tricky.

Sun kept changing the rules regarding what and how things need to be done with Swing with basically each Java release.

At this point it basically became: anything that is not explicitely documented as being thread-safe MUST be done on the EDT (Event Dispatch Thread) once a component is realized.

Note that the show() method is deprecated. Don't use show, there's no guarantee that deprecated method will continue to work in future release. Use setVisible(true) instead.

Calling setVisible(true) shall realize the component, so after that everything that has something to do with Swing and that is not documented as being thread-safe MUST be called on the EDT.

I was a bit quick to say that you were violating the EDT rule in the simple example you gave, but anyway to be on the safe side I'd do the following:

Code:
    public static void main(String[] args) {
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                final JFrame frame = new JFrame("Range Balancer by jwc529");
                frame.setSize(275, 125);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                });
                Container contentPane = frame.getContentPane();
                contentPane.add(new Randomizer());
                frame.setVisible( true );
            }
        } );
    }
SwingUtilities.invokeLater(...) ensures that you're doing Swing/GUI related work on the EDT and frame.show() has been replaced by setVisible(true).

Note that even if in your simple example you were not violating the EDT rule, an automated "EDT violation checker" would still report your version as violating the EDT rule.

Later, once your program starts to get more complicated things gets tricky because the computation you're doing in your listener/callback should not happen on the EDT, because otherwise you're violating another basic rule:

do not do any lenghty computation on the EDT.

And then comes the joy of writing correctly synchronized multi-threaded applications

Multi-thread/synchronization/concurrency is usually the cause of a lot of trouble and many programmers simply cannot get this right. If you look at HEM for example, it used to be prone to spew "concurrency errors / concurrent modification exception" (or whatever .Net/C# calls them), at least in various post 1.0 HEM versions I tried.
Range Balance Software (java) Quote
04-06-2009 , 06:30 PM
Wow, Enjoyed reading this thread, although I have no clue what you guys are talking about
Range Balance Software (java) Quote
04-06-2009 , 08:45 PM
thanks for advice guys, I'll try to look into it

the only GUI experience I have is mostly qt w/ c++ in linux, and java mostly servlets

I wrote this with netbeans but couldn't figure out how to lay it out to preview without running it, it mostly just arranged it by how I added things in the code.
I noticed the deprecation warnings but was mostly just playing around with different functions and was happy it ran.

any decent swing/netbeans guides on the web or API?
Range Balance Software (java) Quote
04-07-2009 , 06:40 AM
Quote:
Originally Posted by jwc529
any decent swing/netbeans guides on the web or API?
I'm using a commercial (very expensive) IDE so I don't know much about NetBeans but AFAIK the NetBeans Swing UI Designer is called "Matisse".

You probably want to Google on "Swing NetBeans Matisse".
Range Balance Software (java) Quote
04-07-2009 , 07:41 AM
Quote:
Originally Posted by contravariance
I'm using a commercial (very expensive) IDE so I don't know much about NetBeans but AFAIK the NetBeans Swing UI Designer is called "Matisse".

You probably want to Google on "Swing NetBeans Matisse".
Can you share what editor this is? Im not satisfied with netbeans swing editor and eclipse has never satisfied me with anything so far so I would really like to know.
Range Balance Software (java) Quote
04-07-2009 , 09:14 AM
Quote:
Originally Posted by dw33p
Can you share what editor this is? Im not satisfied with netbeans swing editor and eclipse has never satisfied me with anything so far so I would really like to know.
Yup... It's IntelliJ IDEA by JetBrains, which has its own Swing GUI editor, as well as several custom layout managers, full support for JGoodies, etc.

The fact that they're selling $599 commercial licences of their IDE when there are IDEs like NetBeans and Eclipse available for free speaks volume in my opinion.

It's the defacto Java IDE in the banking world. Some Fortune 100 companies like Walmart have a "any IDE you want" policy for their developers, because they know that if they were to force a Java developer used to IntelliJ IDEA to use Eclipse he would become mad and fall into depression.

My personal opinion is that in a few years Eclipse / NetBeans will be as good as IntelliJ IDEA but at this point IntelliJ IDEA is an F-22 and Eclipse / NetBeans are plane fighters from the 2nd world war

Their Swing GUI designer completely rocks and their IDE hides all the Swing boilerplate code that you don't care about automatically.

By the way IntelliJ IDEA itself is usually considered to be the best Swing app ever written. It works on Linux, OS X and Windows (thanks Java!). They've won so many software awards that they probably lost track of several of them.

It is often said that IBM/Eclipse came with SWT because they didn't understand Swing. IntelliJ IDEA is an example of programmers who understood Swing

Note that with that much power comes some complexity: a simple "Hello, world!" app may look a little bit intimidating with all the options availabe.

There's a 30 days trial version available and they have a lot of videos (Flash demos)/tutorials etc.

Individual developer licence $249, academic licence $99.

As a sidenote I was also very dissatisfied with Eclipse: it's not that their Emacs-mode was broken, it's that it was differently broken at each release

So now since years I use IntelliJ IDEA with an Emacs plugin.

Last edited by _dave_; 04-07-2009 at 02:28 PM.
Range Balance Software (java) Quote
Range Balance Software (java)
150% up to $2,000 Welcome Bonus on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Range Balance Software (java)

      
m