Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 300,455 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,600 people online right now. Registration is fast and FREE... Join Now!




Breaking array bounds..for some reason

 

Breaking array bounds..for some reason

tralioc81

2 Jul, 2009 - 05:51 PM
Post #1

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
Ok so I use an endless for loop in my program to display the current item in an array, at least I used to. The original code looked like this and it worked fined. I never broke the array bounds and everything was peachy.

CODE

for(counter = 0;;)        //loop to print items one at a time finally..
          {
            if(counter < 0)        //return to last item if under
                counter = dvd.movie.length-1;
            
            if(counter >= dvd.movie.length)        //return to first item if over
                counter = 0;
            
            info.setText(dvd.printItems(counter));    //Print out the items in the inventory    
          }


The new code looks like this. The array is of an object with 6 different variables so in the second set of code I split up the output into six JTextFields instead of one JTextArea. Does this make sense to anyone, or does anybody know what the difference might be? I can post the full code of all my classes, but I warn you it is lengthy and written by a total noob..which is me haha.

CODE

for(counter = 0;;)        //loop to print items one at a time finally..
          {            
            if(counter < 0)        //return to last item if under
                counter = dvd.movie.length-1;
            
            if(counter >= dvd.movie.length)        //return to first item if over
                counter = 0;
            
                                                        //Print out the items in the inventory
            itemNumber.setText(dvd.number(counter));
            itemTitle.setText(dvd.title(counter));
            itemUnits.setText(dvd.units(counter));
            itemPrice.setText(dvd.price(counter));
            itemTotal.setText(dvd.total(counter));
            itemLength.setText(dvd.length(counter));            
          }


User is offlineProfile CardPM
+Quote Post


pbl

RE: Breaking Array Bounds..for Some Reason

2 Jul, 2009 - 06:44 PM
Post #2

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,537



Thanked: 1126 times
Dream Kudos: 450
My Contributions
a serious bad design here

CODE

for(counter = 0;;)        //loop to print items one at a time finally..
          {            
            if(counter < 0)        //return to last item if under
                counter = dvd.movie.length-1;

if you start your for loop by initiatlizing counter to 0
why would you check if counter < 0 as the first statement in your loop ?
this done I wouldn't bother to check for the rest of your loop code :-)

actually I have seen infinite loop with that syntax

for(;;) to loop forever

but never seen a for loop with initialisation of a variable

for(counter = 0;;) and nothing else ... this syntax is really ackward

This post has been edited by pbl: 2 Jul, 2009 - 07:36 PM
User is offlineProfile CardPM
+Quote Post

bbq

RE: Breaking Array Bounds..for Some Reason

2 Jul, 2009 - 07:15 PM
Post #3

omgwtfbbq
Group Icon

Joined: 15 May, 2008
Posts: 725



Thanked: 64 times
Dream Kudos: 125
My Contributions
java
for (int counter = 0; counter < 50; counter++)
{
if (counter >= dvd.movie.length)
// do stuff
else
// do other stuff
}


As pbl said "this syntax is really ackward"

confused.gif
User is offlineProfile CardPM
+Quote Post

tralioc81

RE: Breaking Array Bounds..for Some Reason

3 Jul, 2009 - 02:22 AM
Post #4

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
ok I changed the initialization of the loop to
CODE

for(;;)


but it doesn't make much difference. The idea of the loop was what keeps the program running, so the loop was only ever initialized that one time before.

The buttons and action listeners do all the work of navigating the array and then the statements within this loop print the results to some text fields. It used to work ok with one JtextArea getting printed to. Now that I am using a number of JtextFields its telling me I'm either out of the array -1 below, or +1 over when I navigate around. Its really flaky too, like sometimes I can go through the whole set and the if statement will reset it, but most of the time it doesn't get the chance. I don't know why the two if statements aren't keeping it in check any more.


User is offlineProfile CardPM
+Quote Post

tralioc81

RE: Breaking Array Bounds..for Some Reason

3 Jul, 2009 - 10:26 AM
Post #5

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
well I fixed it for now. I put the if statements in with the action listeners, so they get done immediately after those actions take place. I used a static variable to reference the array length inside the methods for those listeners.
User is offlineProfile CardPM
+Quote Post

pbl

RE: Breaking Array Bounds..for Some Reason

3 Jul, 2009 - 12:26 PM
Post #6

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,537



Thanked: 1126 times
Dream Kudos: 450
My Contributions
QUOTE(tralioc81 @ 3 Jul, 2009 - 10:26 AM) *

well I fixed it for now. I put the if statements in with the action listeners, so they get done immediately after those actions take place. I used a static variable to reference the array length inside the methods for those listeners.

There must be a better way than a static method
If the listeners are within your class they will see any instance variable
If they are outside, you can pass the instance of your class in the constructor of the listener

CODE

class Abc {
   int index;
   {
        
         component.addListener(new MyListener(this));
....

class MyListener implements ActionListener {
      Abc abc;
      // constructor
      MyListener(Abc abc) {
          this.abc = abc;
      ...
      public void ActionPerformed(ActionEvent e) {
          abd.index = .....
....


Anyhow icon_up.gif

This post has been edited by pbl: 4 Jul, 2009 - 06:59 AM
User is offlineProfile CardPM
+Quote Post

tralioc81

RE: Breaking Array Bounds..for Some Reason

3 Jul, 2009 - 01:37 PM
Post #7

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
Thanks I got it to work just accessing the instance variable now instead of creating a static one. I didn't realize I could do this before because when I was trying it, the variable was declared 'after' my action listeners. I'm pretty sure I remember reading that variables generally have to be defined before I try to use them. blink.gif

This will make it easier to do the rest of the tasks I need to do in this assignment.
User is offlineProfile CardPM
+Quote Post

tralioc81

RE: Breaking Array Bounds..for Some Reason

3 Jul, 2009 - 03:25 PM
Post #8

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
Ok I thought I had it. now I am getting this message from inside the action listeners.

cannot refer to a non-final variable myVariable inside an inner class defined in a different method.

Everything is in the same class. Is making any variable final that I want access to the only option?

This post has been edited by tralioc81: 3 Jul, 2009 - 03:50 PM
User is offlineProfile CardPM
+Quote Post

pbl

RE: Breaking Array Bounds..for Some Reason

3 Jul, 2009 - 07:33 PM
Post #9

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,537



Thanked: 1126 times
Dream Kudos: 450
My Contributions
Post your code
Your are asking mechanics "fixed my car without opening the hood"
User is offlineProfile CardPM
+Quote Post

tralioc81

RE: Breaking Array Bounds..for Some Reason

4 Jul, 2009 - 05:16 AM
Post #10

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
ok here is the class I am having issues with
CODE

class Program
{
static int counter = 0;

    public void runProgram()
    {
    Inventory dvd = new Inventory();    //Create an Inventory Object
    
    JFrame gui = new JFrame("Inventory Program Part 4");    //Create Main Frame
    gui.setSize(600, 500);                                                        
    gui.setVisible(true);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
    JPanel noticePanel = new JPanel();                        //Create panels to display text
    JPanel headingPanel = new JPanel();
    //JPanel itemInfoPanel = new JPanel();
    JTextField itemNumber = new JTextField();
    JTextField itemTitle = new JTextField();
    JTextField itemUnits = new JTextField();
    JTextField itemPrice = new JTextField();
    JTextField itemTotal = new JTextField();
    JTextField itemLength = new JTextField();
    JPanel totalPanel = new JPanel();
    JButton next = new JButton("Next Item");                //create the buttons
    JButton first = new JButton("First Item");
    JButton previous = new JButton("Previous Item");
    JButton last = new JButton("Last Item");
    next.setPreferredSize(new Dimension(100, 25));
    first.setPreferredSize(new Dimension(125, 25));
    previous.setPreferredSize(new Dimension(150, 25));
    last.setPreferredSize(new Dimension(100, 25));
    JButton addItem = new JButton("Add Item");
    JButton modifyItem = new JButton("Modify Item");
    JButton deleteItem = new JButton("Delete Item");
    Icon companyLogo = new ImageIcon("logo.jpg");        //load the company logo image
    JLabel logo = new JLabel(companyLogo);
    logo.setIcon(companyLogo);
    logo.setToolTipText("My Company is awsome");
    
    
    
    
    next.addActionListener(new ActionListener()            //next button action control
    {
      public void actionPerformed(ActionEvent evt)
      {
        counter++;
        if(counter < 0)        //return to last item if under
            counter = dvd.movie.length-1;
        
        if(counter >= dvd.movie.length)        //return to first item if over
            counter = 0;
      }
    });
    first.addActionListener(new ActionListener()                //next button action control
    {
      public void actionPerformed(ActionEvent evt)
      {
        counter = 0;
      }
    });
    previous.addActionListener(new ActionListener()                //next button action control
    {
      public void actionPerformed(ActionEvent evt)
      {
        counter--;
        if(counter < 0)        //return to last item if under
            counter = dvd.movie.length-1;
        
        if(counter >= dvd.movie.length)        //return to first item if over
            counter = 0;
      }
    });
    last.addActionListener(new ActionListener()                //next button action control
    {
      public void actionPerformed(ActionEvent evt)
      {
        counter = -1;
        if(counter < 0)        //return to last item if under
            counter = dvd.movie.length-1;
        
        if(counter >= dvd.movie.length)        //return to first item if over
            counter = 0;
      }
    });
    addItem.addActionListener(new ActionListener()                //next button action control
    {
      public void actionPerformed(ActionEvent evt)
      {
          itemTitle.setText(dvd.title(counter));
          itemUnits.setText(dvd.units(counter));
          itemPrice.setText(dvd.price(counter));
          itemTotal.setText(dvd.total(counter));
          itemLength.setText(dvd.length(counter));
      }
    });
    
    FlowLayout layout = new FlowLayout();                //setup layout manager for frame
    gui.setLayout(layout);
    JTextArea notice = new JTextArea(1,1);                //create text areas to display text
    JTextArea heading = new JTextArea(1,1);
    //JTextArea info = new JTextArea(1, 1);
    JTextArea total = new JTextArea(1, 1);
    heading.setSize(1, 1);
    gui.add(logo);
    gui.add(noticePanel);                            //add panels and button to the gui
    gui.add(headingPanel);
    //gui.add(itemInfoPanel);
    gui.add(itemNumber);
    gui.add(itemTitle);
    gui.add(itemUnits);
    gui.add(itemPrice);
    gui.add(itemTotal);
    gui.add(itemLength);
    gui.add(totalPanel);
    gui.add(first, layout);
    gui.add(previous, layout);
    gui.add(next, layout);
    gui.add(last, layout);
    gui.add(addItem, layout);
    gui.add(modifyItem, layout);
    gui.add(deleteItem, layout);
    noticePanel.add(notice);                        //put the information from other methods into gui
    headingPanel.add(heading);
    //itemInfoPanel.add(info);
    totalPanel.add(total);
    

    
    //*****************************************************
    
    
                                        //To allow access to its methods
    
    dvd.fillArray();                //populate and sort the array of items
    dvd.sortArray();
    
    notice.setText(dvd.printNotice());                //print notice and heading
    heading.setText(dvd.printHeadings());
    total.setText(dvd.calculateGrandTotal());            //print grand total
    for(;;)        //loop to print items one at a time finally..
        {
                                                    //Print out the items in the inventory
        itemNumber.setText(dvd.number(counter));
        itemTitle.setText(dvd.title(counter));
        itemUnits.setText(dvd.units(counter));
        itemPrice.setText(dvd.price(counter));
        itemTotal.setText(dvd.total(counter));
        itemLength.setText(dvd.length(counter));            
        }
    }
}


In the first line of the method I create dvd, which is a new inventory object. I can reference it just fine down in the for loop at the bottom. What it won't let me do is reference dvd from inside the action listeners. Eclipse tells me I have to set dvd to final in order to refer dvd from within those.

The same goes for the one action listener named addItem. I was going to try and work with all the JTextfields from that one, but I am getting the same error there.


User is offlineProfile CardPM
+Quote Post

pbl

RE: Breaking Array Bounds..for Some Reason

4 Jul, 2009 - 06:57 AM
Post #11

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,537



Thanked: 1126 times
Dream Kudos: 450
My Contributions
Where is your class ActionListener ?
User is offlineProfile CardPM
+Quote Post

tralioc81

RE: Breaking Array Bounds..for Some Reason

4 Jul, 2009 - 07:41 AM
Post #12

New D.I.C Head
*

Joined: 13 Jun, 2009
Posts: 12


My Contributions
import java.awt.event.ActionListener;

Its a built in class. I was just using the action listeners in the Program class.
User is offlineProfile CardPM
+Quote Post

pbl

RE: Breaking Array Bounds..for Some Reason

4 Jul, 2009 - 09:07 AM
Post #13

Java Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 9,537



Thanked: 1126 times
Dream Kudos: 450
My Contributions
QUOTE(tralioc81 @ 4 Jul, 2009 - 07:41 AM) *

import java.awt.event.ActionListener;

Its a built in class. I was just using the action listeners in the Program class.

It is not a class it is an interface biggrin.gif
You'll have to wrote your own as MyListener that I gave you as example 3 or 4 posts before
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/8/09 01:59AM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month