Member Avatar for mehnihma

I need help with this code. I get zero values, how can I stop generating numbers when I hit the target number?
Thanks

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.concurrent.locks.ReentrantLock;

    /**
     * @author Marin 
     */
    public class TargetFinder extends JFrame {

        private static final long serialVersionUID = 1L;
        private JPanel panel, panel2, panel3, panel4;
        private JLabel lMax, lTarget, lBuffer;
        private JTextField tMax, tTarget, tBuffer;
        private JTextArea area;
        private JButton btnStart,btnReset,btnExit;
        private static ArrayList<Integer> numbers = new ArrayList<Integer>();
        private static Thread t1;
        private static ReentrantLock lock = new ReentrantLock();
        private static int x, maxNum,maxTarget;

        /**
         * Constructor for target Finder
         */
        public TargetFinder() {

            // create panels

            // First row with text

            panel = new JPanel();
            panel.setLayout(new FlowLayout());

            // create TextFields and labels and add them to panel

            lMax = new JLabel("Max #");
            tMax = new JTextField(8);

            lTarget = new JLabel("Target #");
            tTarget = new JTextField(6);

            lBuffer = new JLabel("Buffer ");
            tBuffer = new JTextField(8);
            tBuffer.setEditable(false); // cannot edit buffer

            panel.add(lMax);
            panel.add(tMax);
            panel.add(lTarget);
            panel.add(tTarget);
            panel.add(lBuffer);
            panel.add(tBuffer);

            // create text Field
            panel2 = new JPanel();

            area = new JTextArea(20,40);
            area.setLineWrap(true);
            JScrollPane jsp = new JScrollPane(area);


            panel2.add(jsp);

            // add buttons

            panel3 = new JPanel();

            btnStart = new JButton("Start");
            btnStart.setMnemonic('S');

            btnReset = new JButton("Reset");
            btnReset.setMnemonic('R');

            btnExit = new JButton("Exit");
            btnExit.setMnemonic('x');

            //add buttons to panel

            panel3.add(btnStart);
            panel3.add(btnReset);
            panel3.add(btnExit);

            // add action listeners for buttons

            btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae)
                    {
                    //TODO Start threads

                    // Check for input empty or letters
                    if (tMax.equals("") || tTarget.equals(""))
                    {
                        JOptionPane.showMessageDialog(null, "Please enter a postive number", "Message", JOptionPane.ERROR_MESSAGE);


                    }
                    else{


                        try{
                              // System.out.print(numbers.get(j) + " ");
                            maxNum = Integer.parseInt(tMax.getText()); // parse to integer
                            maxTarget = Integer.parseInt(tTarget.getText()); // parse to integer
                            Random rand = new Random(); // random nuber generator
                            // check if the target number is smaller then max number
                            if (maxTarget < maxNum)
                            {
                            x = rand.nextInt(maxNum + 1); // set maximum number

                               //area.append(x+" ");
                               // thread for writing random numbers


                               t1 = new Thread(new Writer(x));
                               t1.start();
                               Thread read = new Thread(new Reader());





                            }
                            else
                            {
                                JOptionPane.showMessageDialog(null, "Please enter a target number < Max #", "Message", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                        catch (NumberFormatException numB)
                        {
                            //  WRITE ERROR
                            JOptionPane.showMessageDialog(null, "Please enter a postive number", "Message", JOptionPane.ERROR_MESSAGE);

                        }

                    }






                    }
                });

            // reset button

            btnReset.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae)
                    {

                    area.setText("");
                    tMax.setText("");
                    tTarget.setText("");
                    tBuffer.setText("");

                    // stop threads and reset everything //TODO

                    }
                });


            // exit button

            btnExit.addActionListener(new ActionListener()  {
                public void actionPerformed(ActionEvent ae)
                {

                    System.exit(0);
                }
            });



            // add panels to the frame
            add(panel, BorderLayout.NORTH);
            add(panel2, BorderLayout.CENTER);
            add(panel3, BorderLayout.SOUTH);

            // set the frame

            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();


        }


        public class Writer implements Runnable
        {
            private int x;

            public Writer(int x)
            {
                this.x = x;
            }

            public void run()
            {

                // create a loop and write 
                maxTarget = Integer.parseInt(tTarget.getText()); // parse to integer            
            while(x < maxTarget)
                {

                    if (x == maxTarget)
                    {
                        break;
                    }
                    else
                    {


                        //Random rand = new Random(); // random nuber generator


                        lock.lock();

                        area.append(x+" ");
                        lock.unlock();

                    }




        }




            }
        }


        public class Reader implements Runnable
        {
            //private int randomN;
            public Reader()
            {
                //this.randomN = randomN;
            }

            public void run()
            {

                // create a loop and write 




            }
        }



        /**
         * @param args
         */
        public static void main(String[] args) {

            new TargetFinder();  // run 

        }

    }

how can I stop generating numbers when I hit the target number

Where do you get the numbers? When you get the target number, stop asking for any more numbers. Either exit the loop or return from the method when the target number is hit.

Your code has too many blank lines. That makes it harder to read.

Member Avatar for mehnihma

in this part I get numbers

    try {
                    // System.out.print(numbers.get(j) + " ");
                    maxNum = Integer.parseInt(tMax.getText()); // parse to
                                                                // integer
                    maxTarget = Integer.parseInt(tTarget.getText()); // parse
                                                                        // to
                                                                        // integer
                    Random rand = new Random(); // random nuber generator
                    // check if the target number is smaller then max number
                    if (maxTarget < maxNum) {
                        x = rand.nextInt(maxNum + 1); // set maximum number

                        // area.append(x+" ");
                        // thread for writing random numbers

                        t1 = new Thread(new Writer(x));
                        t1.start();
                        Thread read = new Thread(new Reader());

                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Please enter a target number < Max #",
                                "Message", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException numB) {
                    // WRITE ERROR
                    JOptionPane.showMessageDialog(null,
                            "Please enter a postive number", "Message",
                            JOptionPane.ERROR_MESSAGE);

and I print them here

    public class Writer implements Runnable {
        private int x;

        public Writer(int x) {
            this.x = x;
        }

        public void run() {

            // create a loop and write
            maxTarget = Integer.parseInt(tTarget.getText()); // parse to integer
            while (x < maxTarget) {

                if (x == maxTarget) {
                    break;
                } else {

                    // Random rand = new Random(); // random nuber generator

                    lock.lock();

                    area.append(x + " ");
                    lock.unlock();

                }

            }

        }
    }

The loop at line 12 looks like it needs the value of x to change. Where does the code change the value of x?
Also Look at the logic of the test of values on line 12 and line 14. If the first is true, when will the second be true?

Try debugging the code by Adding some printlns to show the values of all the variables the code uses.

Member Avatar for mehnihma

if i put like this I get just zeros, and if I just add area.append(x + ""); it works normaly?

while (true) {
                if (x == maxTarget) {
                    break;
                } else {
                    // Random rand = new Random(); // random nuber generator
                    lock.lock();
                    area.append(x + " ");
                    lock.unlock();
                }

Did you try adding the printlns?
where is the value of changed? If it is 0 it will stay 0

Member Avatar for mehnihma

It prints good values
If I put max 3 and target 1
it prints 0 1 2 3 but it print evey number bilion time and it does not stop? And when it comes to 0 again it just prints 0

it does not stop?

What will change the looping so it will stop? while(true) will loop forever.
Remove the while loop and it will stop looping.

Member Avatar for mehnihma

I need to write the values until it prints the taraget value
How can I do it?

When you get the value, write it there and not in a loop in another class and method.

What was the problem with line 13? You have it commented out. That would be the place to do it.

Member Avatar for mehnihma

I have sloved it, the problem was that I have been passing generated value in the thread

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.