Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2005

Tip: Looking for answers? Try searching our database.

Newbie - App button only works once

Thread view: 
Cardinal - 10 Nov 2005 16:48 GMT
I have what is meant to be a "humorous" application whereby when the
user clicks the "New Cliche" button they receive a new, trite, business
cliche. This is adopted from one of the examples in the "Head First
Java" book. Anyway, it works but only for one click. When the user
clicks the first time, the text field populates with a cliche. The
second click however does not change the saying which is what I would
like it to do. Can someone offer a suggestion on what I can do to make
it change *each* time the user clicks the button. Thank you very much.

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

//implements the action listener interface
class WorkCliches extends JFrame implements ActionListener
{
    JButton b1 = new JButton("New Cliche");
    JTextField mySaying = new JTextField("", 34);
    PhraseOMatic myPhrase = new PhraseOMatic();

    public WorkCliches()
    {
        super("Sayings to Look Smart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //the next two lines add action listeners
        //to both JButton objects
        b1.addActionListener(this);

        FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
        setSize(450, 120);
        setLayout(flow);
        add(b1);
        add(mySaying);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent evt)
    {
        //evt object's getSource() method determines
        //the source of the event.
        Object source = evt.getSource();
        if (source == b1)
        {
            mySaying.setText(myPhrase.phrase);
        }

    }

    public static void main(String[] args)
    {
        WorkCliches frame = new WorkCliches();
    }   
}
klynn47@comcast.net - 10 Nov 2005 17:50 GMT
Have you checked to make sure that myPhrase.phrase is giving you a new
phrase?
Cardinal - 10 Nov 2005 18:13 GMT
Yes. When I close out the app and re-start it, that first click gives
me a different phrase from the first time.
Every time that I restart the app - it gives me a different phrase so I
think my random from an array is working. Here is the code to the
"phrase-o-matic" after I tweaked it. Thanks.

class PhraseOMatic
{
        //Three sets of words to choose from

        String[] wordListOne =
        {
            "24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win",
            "front-end","web-based", "pervasive", "smart", "six-sigma",
            "critical-path", "dynamic"
        };

        String[] wordListTwo =
        {
            "Empowered", "sticky", "value-added", "oriented", "centric",
            "distributed","clustered", "branded", "outside-the-box",
"positioned",
            "networked", "focused", "leveraged", "aligned", "targeted",
"shared",
            "cooperative", "accelerated"
        };

        String[] wordListThree =
        {
            "process", "tipping-point", "solution", "architecture", "core
competency",
            "strategy","mindshare", "portal", "space", "vision",
            "paradigm", "mission"
        };

        //how many words in each list

        int oneLength = wordListOne.length;
        int twoLength = wordListTwo.length;
        int threeLength = wordListThree.length;

        //generate three random numbers

        int rand1 = (int) (Math.random() * oneLength);
        int rand2 = (int) (Math.random() * twoLength);
        int rand3 = (int) (Math.random() * threeLength);

        //build a phrase
        String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " +

            wordListThree[rand3];
   
}
klynn47@comcast.net - 10 Nov 2005 18:21 GMT
I would recommend changing your setText to a simple print out inside
the actionPerformed so that you can make sure that a new call to
myPhrase.phrase gives you a new phrase.

System.out.println(myPhrase.phrase);
Cardinal - 10 Nov 2005 19:14 GMT
Thanks but when I tried your suggestion, it placed the results in the
console at the bottom of the screen instead of the application itself.
Also, unfortunately, it did not change the phrase. Everytime I clicked
the button it repeated the same phrase over and over in the console
area. I appreciate the help though.
Monique Y. Mudama - 11 Nov 2005 23:37 GMT
> Thanks but when I tried your suggestion, it placed the results in
> the console at the bottom of the screen instead of the application
> itself.  Also, unfortunately, it did not change the phrase.
> Everytime I clicked the button it repeated the same phrase over and
> over in the console area. I appreciate the help though.

I believe the person to whom you were referring meant the results to
be placed on the console, not the gui.  This way you can check to see
if your random phrase generator is working properly without worrying
about issues of refreshing, etc.  It's just one step in trying to
narrow down the root cause of the bug.

By the way, it's a lot easier to follow a discussion and figure out
what's going on if you quote the relevant sections of the previous
post.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

klynn47@comcast.net - 10 Nov 2005 18:25 GMT
After looking at the code in PhraseOMatic, the problem is that you only
generate one random number. When you call myPhrase.phrase, it will pick
up the same one each time. What you need to do is create a method in
PhraseOMatic that will generate a random phrase, and then call that
method.
klynn47@comcast.net - 10 Nov 2005 18:27 GMT
I meant to say one random phrase.
jonck@vanderkogel.net - 10 Nov 2005 19:06 GMT
> After looking at the code in PhraseOMatic, the problem is that you only
> generate one random number.

Indeed. You want to alter your PhraseOMatic class a bit.

/*
* NOTE: untested code
*/
class PhraseOMatic {
    Random random = new Random();

    //Three sets of words to choose from

    String[] wordListOne = {
        "24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win",
        "front-end","web-based", "pervasive", "smart", "six-sigma",
        "critical-path", "dynamic"};

    String[] wordListTwo = {
        "Empowered", "sticky", "value-added", "oriented", "centric",
        "distributed","clustered", "branded", "outside-the-box",
        "positioned", "networked", "focused", "leveraged", "aligned",
        "targeted", "shared", "cooperative", "accelerated"};

    String[] wordListThree = {
        "process", "tipping-point", "solution", "architecture",
        "core competency", "strategy","mindshare", "portal", "space",
        "vision", "paradigm", "mission"};

    public String getNewPhrase() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(wordListOne[random.nextInt(wordListOne.length - 1)]);
        buffer.append(wordListTwo[random.nextInt(wordListTwo.length - 1)]);
        buffer.append(wordListThree[random.nextInt(wordListThree.length -
1)]);

        return buffer.toString();
    }
}

Then in your actionPerformed method:

mySaying.setText(myPhrase.getNewPhrase());

Note how I used the java.util.Random instead of Math.random(). If you
want to read why this is better, read
http://mindprod.com/jgloss/gotchas.html#RANDOM

Kind regards, Jonck
jonck@vanderkogel.net - 10 Nov 2005 19:16 GMT
> buffer.append(wordListOne[random.nextInt(wordListOne.length - 1)]);
> buffer.append(wordListTwo[random.nextInt(wordListTwo.length - 1)]);
> buffer.append(wordListThree[random.nextInt(wordListThree.length - 1)]);

Small correction, the -1 should be left out, since nextInt produces
numbers from 0 to n-1 instead of from 0 to n (as my code assumed).
Cardinal - 10 Nov 2005 20:03 GMT
ah man - I'm happy. It now works as envisioned!
Thanks everyone.
(I'm lovin' this java thing.)
Oliver Wong - 10 Nov 2005 20:38 GMT
> Note how I used the java.util.Random instead of Math.random(). If you
> want to read why this is better, read
> http://mindprod.com/jgloss/gotchas.html#RANDOM

   I took a look at the page and I couldn't see why using java.util.Random
is better than Math.random(). Can you elaborate?

   - Oliver
jonck@vanderkogel.net - 10 Nov 2005 21:50 GMT
> I took a look at the page and I couldn't see why using java.util.Random
> is better than Math.random(). Can you elaborate?

Hmm... I was under the impression that Math.Random created "less
random" numbers (and that I had read that at Roedy's site) but I can't
find it anywhere anymore. I guess either my memory is mistaken or I
read it elsewhere. Should I find the source I'll post it here.
jonck@vanderkogel.net - 10 Nov 2005 22:05 GMT
> I took a look at the page and I couldn't see why using java.util.Random
> is better than Math.random(). Can you elaborate?

Well, I can't find the source, but here is how I remember it to be. The
Math.random() function seeds itself with the current time in
milliseconds. Thus, if you call Math.random() three times in a row,
there is the possibility that you will with the same seed each time and
get the same number as a result.
In comparison, if you create a java.util.Random object and call nextInt
3 times in a row, you will be working with one seed and getting the
next three numbers derived from it, thus making things more random.

But I could be wrong, this is how I remember it, but I can't find a
source to corroborate.
Oliver Wong - 10 Nov 2005 22:13 GMT
> Well, I can't find the source, but here is how I remember it to be. The
> Math.random() function seeds itself with the current time in
[quoted text clipped - 7 lines]
> But I could be wrong, this is how I remember it, but I can't find a
> source to corroborate.

   From the Javadocs @
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Math.html#random()

<quote>
When this method is first called, it creates a single new
pseudorandom-number generator, exactly as if by the expression

new java.util.Random

This new pseudorandom-number generator is used thereafter for all calls to
this method and is used nowhere else.
</quote>

   So it looks like Math.random() seeds the random number generator once
(the first time it's used), and never re-seeds it again (special issues
regarding custom class loaders not withstanding).

   I usually instantiate my own RNG instead of using Math.random() anyway,
but still it would have been nice to know if Math.random() really did have a
flaw.

   - Oliver
jonck@vanderkogel.net - 11 Nov 2005 00:02 GMT
> So it looks like Math.random() seeds the random number generator once
> (the first time it's used), and never re-seeds it again (special issues
> regarding custom class loaders not withstanding).

Ok, thanks for putting me in the right.
Bjorn Abelli - 10 Nov 2005 22:11 GMT
<jonck@vanderkogel.net> wrote...

>> I took a look at the page and I couldn't see why using
>> java.util.Random is better than Math.random(). Can you elaborate?
[quoted text clipped - 3 lines]
> find it anywhere anymore. I guess either my memory is mistaken or I
> read it elsewhere. Should I find the source I'll post it here.

It could never create "less random" numbers than using java.util.Random, as
Math.Random *uses* java.util.Random behind the scenes. It's just a
"convenience" method.

However, java.util.Random *itself* is not perfect and creates "less random"
numbers than *other* random number generators, which is discussed on Roedy's
page.

// Bjorn A
Roedy Green - 10 Nov 2005 22:17 GMT
>    I took a look at the page and I couldn't see why using java.util.Random
>is better than Math.random(). Can you elaborate?
you have control over the seeding. This can be useful in debugging if
you want to reproduce a run.
Math.random just gives you a double. java.util.Random has a richer set
of methods.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.