Basic array question, need help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • KellyH

    Basic array question, need help

    Hi, I hope someone can point me in the right direction.
    I'll get it out of the way: Yes, I am a college student. No, I am not
    looking for anyone to do my homework, just looking for help. I have been
    reading this ng all semester, and found it very helpful. I just have a
    stupid problem going on right now.

    Here's the project:
    We have to make a little frame with a text field, where the user inputs a
    number, and a text area where a message is displayed. There are several
    buttons on the frame: Enter, Average, Show Ascending, Show Descending,
    Median, and High Number. We are to use an array to store up to 50 integers
    the user enters.

    Here's my problem:
    My problem is that I can't figure out how to load the array. If I do it in
    the Enter button event, then a new array is created each time an integer is
    entered. I tested this by adding the current int to the int in the previous
    cell. Oh, I am also storing the logical end of the array in the 0 cell. If
    I try to load the array in the main, I get an error: Non-static method
    load_aNum cannot be referenced from a static context. We had a project
    previously where I used two arrays (pre-filled, not using input numbers),
    and I loaded it in the main, and it worked fine. Don't know why this won't
    work.

    What I have so far (I've just been concentrating on getting the user numbers
    to enter into the array. I'll worry about the rest of it later):

    import java.awt.*;
    import java.awt.event. *;
    import java.math.*;
    import java.util.Array s.*; //thought I might need this later for sorting
    the array

    public class khNumberDisplay er extends Frame implements ActionListener
    {

    private Button btnEnter, btnAvg, btnAscend, btnDescend, btnMedian,
    btnHigh;
    private TextField tfNum1 = new TextField (5);

    private TextArea taMessage = new TextArea();

    private int[] aNum;
    private int lastSub =0;


    /** Creates a new instance of khNumberDisplay er */
    public khNumberDisplay er()
    {


    setTitle ("Number Displayer by Kelly");
    setLayout (new FlowLayout());
    add (new Label ("NUMBER "));
    add (tfNum1);

    add (new Label ("Message = "));
    add (taMessage);

    btnEnter = new Button ("Enter");
    add (btnEnter);
    btnEnter.addAct ionListener (new EnterHandler(th is));
    addWindowListen er(new CloseWindow());

    }


    public void load_aNum()
    {
    aNum = new int[50];
    aNum[0]++;
    }

    private static boolean isValid(int pInput)
    {
    boolean bResult;

    bResult = (pInput >=0) && (pInput<=9999);

    return bResult;
    }



    class EnterHandler implements ActionListener

    {
    khNumberDisplay er myFrame;
    EnterHandler (khNumberDispla yer pFrame)
    {
    myFrame=pFrame;
    }
    public void actionPerformed (ActionEvent event)
    {
    myFrame.EnterSt uff();
    myFrame.repaint ();
    }
    }


    public void EnterStuff()
    {
    String sMessage;
    boolean valid_test;
    int num1;

    num1 = Integer.parseIn t(tfNum1.getTex t());

    //valid_test = (num1 >=1 && num1 <=200);
    if (isValid(num1))
    {


    aNum[aNum[0]] = num1;
    int total;
    total = aNum[aNum[0]] + aNum[aNum[0]-1];
    sMessage = "Number is valid. " + total;
    }
    else
    sMessage = "Number is not valid";

    taMessage.setTe xt(sMessage);


    }

    public void actionPerformed (ActionEvent event)
    {
    repaint();
    }

    public static void main (String []args)
    {
    Frame NumberDisplayer Window = new khNumberDisplay er();
    NumberDisplayer Window.setSize (700,300);
    NumberDisplayer Window.setBackg round(Color.pin k);
    NumberDisplayer Window.show();
    load_aNum();
    }

    public class CloseWindow extends WindowAdapter
    {
    public void windowClosing (WindowEvent e)
    {
    System.exit(0);
    }
    }

    }
    --
    -Kelly
    kelly at farringtons dot net
    Check out www.snittens.com


  • Chris Shepherd

    #2
    Re: Basic array question, need help

    KellyH wrote:[color=blue]
    > Here's my problem:
    > My problem is that I can't figure out how to load the array. If I do it in
    > the Enter button event, then a new array is created each time an integer is
    > entered. I tested this by adding the current int to the int in the previous
    > cell. Oh, I am also storing the logical end of the array in the 0 cell. If
    > I try to load the array in the main, I get an error: Non-static method
    > load_aNum cannot be referenced from a static context. We had a project
    > previously where I used two arrays (pre-filled, not using input numbers),
    > and I loaded it in the main, and it worked fine. Don't know why this won't
    > work.[/color]

    Are you able to make use of the ArrayList object at all? It may be far
    simpler to use that than an actual integer array. Just make sure you use
    Integer.parseIn t() to validate the input, and then add it to your
    ArrayList object (which should, of course, be declared at the class level).

    --
    Chris Shepherd

    Comment

    • Anthony Borla

      #3
      Re: Basic array question, need help


      "KellyH" <Kelly@whatever .com> wrote in message
      news:UqoBb.4845 96$Tr4.1330037@ attbi_s03...[color=blue]
      >
      > Hi, I hope someone can point me in the right direction.
      > I'll get it out of the way: Yes, I am a college student.
      > No, I am not looking for anyone to do my homework,
      > just looking for help. I have been reading this ng all
      > semester, and found it very helpful. I just have a
      > stupid problem going on right now.
      >
      > Here's the project:
      > We have to make a little frame with a text field, where
      > the user inputs a number, and a text area where a message
      > is displayed. There are several buttons on the frame:
      > Enter, Average, Show Ascending, Show Descending,
      > Median, and High Number. We are to use an array to store
      > up to 50 integers the user enters.
      >
      > Here's my problem:
      > My problem is that I can't figure out how to load the array.
      > If I do it in the Enter button event, then a new array is created
      > each time an integer is entered. I tested this by adding the
      > current int to the int in the previous cell. Oh, I am also
      > storing the logical end of the array in the 0 cell. If I try to
      > load the array in the main, I get an error: Non-static method
      > load_aNum cannot be referenced from a static context.
      > We had a project previously where I used two arrays
      > (pre-filled, not using input numbers), and I loaded it in the
      > main, and it worked fine. Don't know why this won't work.
      >
      > What I have so far (I've just been concentrating on getting
      > the user numbers to enter into the array. I'll worry about the
      > rest of it later):
      >[/color]
      <SNIP CODE>[color=blue]
      >[/color]

      I didn't look at your code, but will give you some general pointers:

      * Since the array size has a known, maximum size [50 ?]
      create it at program startup / initialisation time e.g

      // Note: This is an example - your code may be
      // different
      int array = new array[50];

      You will note that such an array is automatically zero-filled; you
      can use this value as an 'empty element' marker. If you need
      to use zero as a valid value, then fill the array with an arbitrary
      value [say -1 ?] to act in this role

      * Each time the input routine successfully completes add the value
      to the array by incrementing an index e.g.

      ...
      if (nextElement < array.length)
      {
      array[nextElement] = inputValue;
      ++nextElement;
      }
      ...

      'nextElement' will always point to the next enpty array
      element.

      * If not all elements have been filled you can still traverse
      the array [and know when to stop] by checking the
      current element value for -1.

      This allows you to display, or otherwise manipulate
      array contents even if it is not full

      * If you need to have some sort of 'reset' operation,
      ensure all it does is refill the array with -1 values. You
      don't have to recreate the array again

      I hope this helps.

      Anthony Borla


      Comment

      • Karl von Laudermann

        #4
        Re: Basic array question, need help

        "KellyH" <Kelly@whatever .com> wrote in message news:<UqoBb.484 596$Tr4.1330037 @attbi_s03>...
        [color=blue]
        > Here's my problem:
        > My problem is that I can't figure out how to load the array. If I do it in
        > the Enter button event, then a new array is created each time an integer is
        > entered. I tested this by adding the current int to the int in the previous
        > cell. Oh, I am also storing the logical end of the array in the 0 cell. If
        > I try to load the array in the main, I get an error: Non-static method
        > load_aNum cannot be referenced from a static context. We had a project
        > previously where I used two arrays (pre-filled, not using input numbers),
        > and I loaded it in the main, and it worked fine. Don't know why this won't
        > work.[/color]

        I assume by "load" you mean allocate and initialize. The correct place
        to do it is in the constructor, since that's exactly what constructors
        are for:

        /** Creates a new instance of khNumberDisplay er */
        public khNumberDisplay er()
        {
        // Allocate and initialize array
        aNum = new int[50];
        aNum[0]++;

        setTitle ("Number Displayer by Kelly");
        setLayout (new FlowLayout());
        add (new Label ("NUMBER "));
        add (tfNum1);

        add (new Label ("Message = "));
        add (taMessage);

        btnEnter = new Button ("Enter");
        add (btnEnter);
        btnEnter.addAct ionListener (new EnterHandler(th is));
        addWindowListen er(new CloseWindow());
        }

        The reason you can't access aNum from main is because main is a static
        method, which means it belongs to the khNumberDisplay er class in
        general, not any particular instance of it. Static methods cannot
        access non-static member variables, since static methods can be
        executed even when no instances of the class exist. If you really
        wanted to allocate the array from main rather than the constructor
        (though there's no good reason to), you could do it this way:

        public static void main (String []args)
        {
        Frame NumberDisplayer Window = new khNumberDisplay er();
        NumberDisplayer Window.setSize (700,300);
        NumberDisplayer Window.setBackg round(Color.pin k);
        NumberDisplayer Window.show();

        // Call load_aNum on the instance
        NumberDisplayer Window.load_aNu m();
        }

        Comment

        • KellyH

          #5
          Re: Basic array question, need help


          Thanks everyone for your help! I didn't realize I could instantiate the
          array in the constructor. Got it working now. Moving on to other
          problems...
          --
          -Kelly
          kelly at farringtons dot net
          Check out www.snittens.com

          "Karl von Laudermann" <[email protected] m> wrote in message
          news:e7e6125e.0 312100843.1f874 [email protected] gle.com...[color=blue]
          > "KellyH" <Kelly@whatever .com> wrote in message[/color]
          news:<UqoBb.484 596$Tr4.1330037 @attbi_s03>...[color=blue]
          >[color=green]
          > > Here's my problem:
          > > My problem is that I can't figure out how to load the array. If I do it[/color][/color]
          in[color=blue][color=green]
          > > the Enter button event, then a new array is created each time an integer[/color][/color]
          is[color=blue][color=green]
          > > entered. I tested this by adding the current int to the int in the[/color][/color]
          previous[color=blue][color=green]
          > > cell. Oh, I am also storing the logical end of the array in the 0 cell.[/color][/color]
          If[color=blue][color=green]
          > > I try to load the array in the main, I get an error: Non-static method
          > > load_aNum cannot be referenced from a static context. We had a project
          > > previously where I used two arrays (pre-filled, not using input[/color][/color]
          numbers),[color=blue][color=green]
          > > and I loaded it in the main, and it worked fine. Don't know why this[/color][/color]
          won't[color=blue][color=green]
          > > work.[/color]
          >
          > I assume by "load" you mean allocate and initialize. The correct place
          > to do it is in the constructor, since that's exactly what constructors
          > are for:
          >
          > /** Creates a new instance of khNumberDisplay er */
          > public khNumberDisplay er()
          > {
          > // Allocate and initialize array
          > aNum = new int[50];
          > aNum[0]++;
          >
          > setTitle ("Number Displayer by Kelly");
          > setLayout (new FlowLayout());
          > add (new Label ("NUMBER "));
          > add (tfNum1);
          >
          > add (new Label ("Message = "));
          > add (taMessage);
          >
          > btnEnter = new Button ("Enter");
          > add (btnEnter);
          > btnEnter.addAct ionListener (new EnterHandler(th is));
          > addWindowListen er(new CloseWindow());
          > }
          >
          > The reason you can't access aNum from main is because main is a static
          > method, which means it belongs to the khNumberDisplay er class in
          > general, not any particular instance of it. Static methods cannot
          > access non-static member variables, since static methods can be
          > executed even when no instances of the class exist. If you really
          > wanted to allocate the array from main rather than the constructor
          > (though there's no good reason to), you could do it this way:
          >
          > public static void main (String []args)
          > {
          > Frame NumberDisplayer Window = new khNumberDisplay er();
          > NumberDisplayer Window.setSize (700,300);
          > NumberDisplayer Window.setBackg round(Color.pin k);
          > NumberDisplayer Window.show();
          >
          > // Call load_aNum on the instance
          > NumberDisplayer Window.load_aNu m();
          > }[/color]


          Comment

          Working...