Local variable doesn't update

hello,
in the example below the upper loop doesn't always update the value of the stop-control. why is that?
Solved!
Go to Solution.
Attachments:
local variable .jpg ‏14 KB

That "solution" is no better than your original. Using a property node instead of a local variable gains you absolutely nothing. A property node requires a thread switch to the user interface thread. In some cases this can cause huge performance impacts. I don't know why you don't want to use an event structure. Are you using LabVIEW Base which has no access to event structures? If you must use loops, then a better way to handle a loop that has a long loop time is to actually have the loop time short and then use a case structure to determine if it's time to execute the loop.
Something like this, for example
Attachments:
parallel loops MOD.vi ‏14 KB
parallel loops MOD_BD.png ‏25 KB

Similar Messages

  • How come my local variable is not updating it's value with respect to what's happening in the while loop?

    Hello,
    I am trying to extract data out of a while loop as my declarations update with respect to the iteration number. I have attempted to use both local variables and shift registers, but with no luck.
    I have also done the following example: http://www.ni.com/white-paper/7585/en and it works like a charm.
    I attached the PNG file with local variable declaration circled in red. Will attach a VI in the next respnose.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Local Variable.png ‏366 KB

    OK, looking at the code...
    Can you explain what it is supposed to do? What's the purpose of the value property node read which only seems to update an indicator.
    The inner while loop should proably be a FOR loop, because the number of iterations is known before the loop starts.
    Your use of formula nodes seems overly complicated.
    LabVIEW Champion . Do more with less code and in less time .

  • Programmatically update Combo box won't update its Local variable

    Hello all,
    I followed a tutorial from NI website and programmatically edit items in a combo box. It worked successfully but not for the Local variables. Local variables still retain items that it had before.
    Any suggestions ?
    Thanks !
    Solved!
    Go to Solution.

    You need to programmatically update the value property in order to change what the local variable will return, the value that you will wire doesn't have to match with one of the Strings[] array.
    Perhaps you need to do something like this to update your value to change from "Two" to "Five".

  • AS3 swf doesn't update variables set via javascript

    Can't figure this one out:  I've got a C4 project with 2 slides.  First slide has a button that executes a Javascript call:
    SetStringVariable("myVar");
    Where myVar is an internal C4 user variable with a default value of "Hello World".
    The second slide has myVar being displayed in a text caption.
    I publish the swf (AS3) and add this javascript function to the .htm file:
    function SetStringVariable(n)
         document.getElementById('Captivate').SetVariable(n, "I set my variable!");
         alert("my var: " + document.getElementById('Captivate').GetVariable(n));
    When you run the project on the web, the alert comes up with "I set my variable!" but the caption on slide 2 still says "Hello World".  Not sure why this occurs since I've just done a round trip with the variable.  It's as if C4 assigns the variable behind the scenes, but the UI doesn't update.  This does not occur if the C4 project is published in AS2.
    Anyone experience this?  Any workarounds?  I'd like to be able to use the SetVariable function in AS3 projects.
    TIA,
    Jim Leichliter

    Steve Howard noted that you can edit the CaptivateMainTimeline.as file typically located C:\Program Files\Adobe\Adobe Captivate 4\ActionScript 3.0\.
    First, I added an external callback:
    try{
                   if((ExternalInterface.available == true) && (parent==stage))
                        myTrace("ExternalInterface is available");
                        ExternalInterface.addCallback("cpSetValue", cpSetValue);
                        ExternalInterface.addCallback("cpGetValue", cpGetValue);
                        ExternalInterface.addCallback("mycpSetValue", mycpSetValue);
                        ExternalInterface.addCallback("mycpSetValue2", mycpSetValue2);
                        ExternalInterface.addCallback("cpSetValueJim", cpSetValueJim);
    Then I wrote my handler for the callback function which was a slight modification to the cpSetValue function that was already there:
         //JBL: For External Interface setting any type of value
              public function cpSetValueJim(variable:String, val):void
              //myTrace("cpSetValue variable1 " + variable + " ; val  " + val);
              var arr:Array = variable.split(".");
              var ref = this;
              for(var i=0; i < arr.length -1; i++)
                   ref = ref[arr[i]];
              ref[ arr[arr.length -1] ] = val; // This works fine for numbers, booleans and strings
    Just make sure you publish your project in AS3.
    You can place some js in a captivate button:
    SetStringVariable("NameOfYourUserVariable");
    Modify the published .htm file by placing in this js function.
    function SetStringVariable(n)
         document.getElementById('Captivate').cpSetValueJim(n, "I set my variable!");
         alert("my var: " + document.getElementById('Captivate').GetVariable(n));
    That's powerful stuff.  Thanks Steve (ACE) for pointing this out!  This opens up a whole new world of possibilities.

  • JDev903 debugger doesn't display local variable when debugging into JDK src

    Hi,
    I found that JDev903 debugger doesn't display local variables in the "smart data" and "data" panels when debugging into the JDK src. For most of the time, it only shows "this" object.
    Is this right? How do I setup JDev903 to display local variables in debugger?
    thanks,
    Richard

    Hi Fred,
    Did you forget to put resultFormat=&quot;e4x&quot;?

  • Data Acquisition - using local variables to write data to a file

    Hello,
    I am running a Data Acquisition vi (currently in LabVIEW 7.1 but soon to be updated to 8.2) that collects ~100 parameters of data from several sources contained in a while loop. The current configuration (which I did not write) uses very few subVIs and writes to ~100 local variables to store each parameter. It then reads all the local variables and builds an array of all the strings, converts then to a spreadsheet string, then uses the write characters to file function to append to a datafile. I am trying to clean things up and have came up with subVIs to collect the data from the following sources:
    8 serial port sources collecting btwn 8 and 20 parameters each
    ~15 thermocouple readings
    ~10 analog inputs
    ~20 parameters read off an ARINC 429 bus.
    I have come up with a subVI to read each of the sources and have placed the subVIs in the while loop. Each subVI outputs the data that it collects in array or cluster form. I was wondering how best to write each parameter to a CSV file at between 1 and 10 Hz. Should I write each subVI output to a LV and then read them off as was done before (the difference being that I have reduced the # of LVs to ~10 vs >100?
    I should add that precise timing is not that important, so if all the subVIs are not collecting simultaneously (which I understand that they won't be), it does not really matter.
    Thanks.

    Hi jilla,
    jilla wrote:
    What I think that you are saying is to turn the outputs of the 4 subVIs into inputs of a 5th subVI that writes to the data file. Correct?
    Yes.  It may sound like a fine-point, but I beileve it's better to create a VI specifically for formatting data - in your example, 4 arrays IN, a single string OUT.  Then write the string to file as a seperate operation.  GUI-displayed data can go through a similar transformation, the four arrays wired to a subVI which builds output-structures specifically for display.  It's a beginner's mistake to put lots of individual controls and indicators on the screen when groups of them are naturally related (in an object-oriented sense.)  Use clusters to group related controls - this will keep the diagram much cleaner.
    One more question: at what point (either # of data points or frequency of data collection) does it become necessary to use queues? Thanks.
    Well, there's not really a clearly definable "point".  I'd say if your update-rate climbs above 100Hz, or you witness poor program or system performance, then it's time.  The scenario you've described is a fairly simple acquire/display&log loop - and simple is good.   Then-again people can't see/react-to updates faster than about 10Hz - so it doesn't make sense to sacrifice performance - if performance becomes an issue.
    Re: queues:  Queues are sometimes used to buffer data that's "produced" in one place and "consumed" in another.
    Here, if/when logging data, you're logging with every DAQ.  I wouldn't recommend using a queue to transport data from a "DAQ loop" to a "Logging-loop" - those functions can be in the same loop.  Should/could a queue be used to get data from a "DAQ loop" to update the GUI at a lower frequency?  Sure, but a Notifier might be a better choice.   Further, in the (simple?) program you've described, you might use a case structure (True/False) to only update FP indicators every "X" iterations - a simple solution that doesn't require Queues or Notifiers.
    Cheers!
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • Problem using local variable in event loop

    I have a state machine from which I want to monitor various controls, including "Start" and "Stop" buttons.  Not every state needs to monitor the controls.  At present, most states run timed loops.  In the first state that reads the front panel, I have an Event structure (inside a While loop) that monitors the various controls' Change Value events.  For numeric controls, I update variables (in shift registers) as needed.  The "Start" button is used to end the While loop controlling the Event structure, allowing the State to exit to the next state.
    My problem comes in subsequent states that employ this same idea.  Here, I put a Local Variable bound to the Start button and use the same code, but it frequently happens that when I enter this particular state, I cannot "turn on" the control -- I push the button, but it stays off.  Curiously, if it was On when I enter, I can turn it off, but then I'm stuck not being able to turn it on.
    I mocked up a very simply routine that illustrates this.  There are two sequences (corresponding to the two states).  Both use an Event loop with a local variable bound to my Stop button (really this is an LED control with custom colors).  I've deliberately moved the "initialization" (the declaration of the control in the block diagram) out of the Event loops -- putting it inside the first loop modifies the behavior in another strange way.
    Here's my thinking on how I would expect this to work:  The code outside Event Loop 1 should have little effect.  Assume the Stop button is initially Off.  You will "sit" in Event Loop 1 until you push the Stop button, changing its value to True; this value will be passed out of the Event case and cause the first While loop to exit.  You now enter the second sequence.  As I understand the Exit tunnel, it defaults to "False", so I'd expect to stay in the second Event loop until I turn the Stop button from On to Off, which will pass out a False, and keep me in the While for one more button push.  However, this doesn't happen -- I immediately exit, as though the "True" value of the Stop local variable is being seen and recognized by the Event loop (even though it hasn't changed, at least not in the context of this second loop).
    An even more curious thing occurs if I start this routine with the Stop button turned on.  Now I start in my Event loop waiting for a change, but this time the change will be from On to Off, which won't cause an exit from the frame.  This will be reflected by having the While loop count increment.  We should now be in the state of the example above, i.e. in an Event loop waiting for the control to be pushed again, and turned On.  However, clicking the control has no effect -- I cannot get it to "turn on".
    Where am I going astray in my thinking?  What is it about this method of doing things that violates the Labview paradigm?  As far as I can tell, what I'm doing is "legal", and I don't see the flaw in my reasoning, above (of course not -- otherwise I'd have fixed it myself!).  Note that because I'm using local variables inside Event loops (and I'm doing this because there are two places in my code where I want to do such testing), the Stop control is not latching (as required).  Is there something that gets triggered/set when one reads a latched control?  Do I need to do this "manually" using my local variable?
    I'll try to attach the simple VI that illustrates this behavior.
    Bob Schor
    Attachments:
    Simple Stop Conundrum.vi ‏14 KB

    altenbach wrote:
    Ravens Fan wrote:
    NEVER have multiple event structures that share the same events. 
    Actually, that's OK.  NOT OK is having multiple event structures in the same sequence structure.
    See also: http://forums.ni.com/ni/board/message?board.id=170&message.id=278981#M278981
    That's interesting.  I had always thought I read more messages discouraging such a thing rather than saying it was okay.  Your link lead me to another thread with this message. http://forums.ni.com/ni/board/message?board.id=170&message.id=245793#M245793.  Now that thread was mainly concentrating on registered user events which would be a different, but related animal. 
    So if you have 2 event structures they each have their own event queue?  So if you have a common event, one structure pulls it off its event queue and it does not affect the other structure's event queue?  I guess the inherent problem with this particular VI was that the second event structure locked the front panel.  Since the code never got to that 2nd event structure because the  first loop never stopped because the change was from true to false.  After reading your post and the others, I did some experimentation and turned off the Lock front panel on the 2nd structure, and that prevented the lockup of the program.
    Overall, the example VI still shows problems with the architecture and I think your answer should put the original poster on the right track.  I think as a rule I would probably never put the same event in multiple structures, I feel there are better ways to communicate the same event between different parts of a program,  but I learned something by reading your reply and about how the event structures work in the background.  Thanks.

  • Sampling local variable and synchroniz​e with DAQmx

    Hello, 
    I made a small change in the set-up I used with labview and now when I wanted to change the code I'm having a rather complicated problem.
    In my old set-up I was measuring three variables: x and y with a QPD and the power of a laser with a power detector. I was using the DAQmx and I was getting a matrix with three columns with n (sample rate) values. Now, for various reasons I had to take out the second detector. So now I want to build the same matrix as constructed before, but instead of putting the measured values of the laser power I want to put the theoretical values (they are in a local variable) as I cannot measure them. The problem is that this local variable, in general, changes during the DAQmx acquisition time and I would need to sample it at the same rate as I acquire the data from DAQ and then combine all them. How I could sample this variable and attach it to my DAQ results? DAQmx doesn't accept local variables.
    Thanks

    A local variable is not something standalone. It is always associated with a control or indicator. Hows is it updated?
    From your description, it is not clear what you are doing. Can you show us some code instead?
    (Also be more clear when using acronyms. QPD cound mean many things)
    LabVIEW Champion . Do more with less code and in less time .

  • Local variables for clean code

    A question of style and LV correctness: 
    I'm quite aware of the risks of these guys, but I see no option here. Right now I have a program with ~35 events in an event structure. I have a wire that contains many device settings that only 2 of these events can change. About 6 events in total require the use of the data on this wire.
    Now, I see two choices:
    1) I can use a shift register and drag the stupid wire across 35 frames and then remember to do it in any additional frames when I add more
    2) I can use a local variable.
    This seems much, much cleaner to me, and I see no better way of doing it. My question is, is there? I've looked up feedback nodes, but I think I can only use them in single event cases. Their data doesn't seem accessible beyond one event case. is there some better option? The data on the wire is an array of objects (classes), if that helps. 

    pobrepablo1 wrote:
    Still though, I object on principle to having a wire across every one of my diagrams, it's cluttersome .
    I thought of a compromise, how about I use a shift register but wire it around my event structure, through a case structure breaking the wire only when I need to? i.e. see attached
    So a single thin 1D object across all event cases is more cluttersome than an additional external 2D case structure, partially wired extra tunnels, and all the extra convoluted logic holding it all together? You priorities seem to be biased.
    A nice wire across all cases is much better. It can be read and written in any event case that needs to, and can always be found in exactly the expected location. Remember that a shift register is very efficient. If the data size does not change, it operates fully in place for the duration of the run. It also often contains data that is not directly of interest to the operator so it does not need a display. A local variable requires a front panel object that needs to be updated in the UI thread. In needs a data copy in memory memory for the control/indicator itself as well as another copy for the transfer buffer (because the FP update is asynchronous). Then we have a third copy in the wire itself. Than makes it three copies of your potentially large array. Add another copy for each local variable instance, and you probably end up using 10x more memory compared to a simple shift register. It all adds up!
    Local variables can be placed anywhere and keeping track of them is like herding cats. The next programmer to work on your project will have a hard time tracking them all down. In properly designed code, it is just "follow the wire". Much more clear and almost self documenting.
    LabVIEW Champion . Do more with less code and in less time .

  • Default initialisation of member variables and local variables

    I don't understand why member variables are initialized with default values by Java.
    Objects are initialized with "null" and primitives with "0", except boolean, which is initialized with "false".
    If these variables are used locally they are not initialized. The compiler requires them to be initialized by the programer, for example "String s = null".
    Why? What is the use of that difference?
    And why are arrays always initialized with default values, no matter if they are member variables or local variables? For example String[] s = new String[10]; s[0] to s[9] are initialized with "null", no matter if "s" is a local or member variable.
    Can someone please explain that strange difference, why it is used? To me it has no sense.

    Most of the time I have to initialize a local variable
    with "String s = null" in order to use it because
    otherwise the compile would complain. This is a cheap
    little trick, but I think everyone uses it.
    I wouldn't agree with "most of the time". The only cases where it is almost necessary to do that is when the variable should be initialized in a loop or a try-catch statement, and that doesn't happen too often.
    If local variables were initiliazed automatically without a warning it would be a Bad Thing: the compiler could tell when there is a possibility that a variable hasn't been assigned to and prevent manymanymany NullPointerExceptions on run time.
    And you didn't answer me why this principle is not
    used with arrays if it is so useful as you think.
    Possibly it is much more difficult to analyse the situation in the case of arrays; what if values are assigned to the elements in an order that depends on run time properties such as values returned from a random number generator.
    The more special rules one has to remember, the more
    likely one makes errors.I agree, but what is the rule to remember in this case?

  • Code doesn't update when uploading new files to website.

    code doesn't update when uploading new files to website.   I was using an old DW version for a long time then forced to upgrade when I bought my MacBook Pro. Now when I make changes to my pages and link to new files etc on my harddrive, when i upload the pages it won't image because the code still points to harddrive (this did not used to be a problem)... I manually changed the code on the web host site to point to the site and it loaded fine. But now my files on my harddrive also point to the web host files and now don't image on my computer. I never had to worry about this so far and wonder if the new version has a setting I'm supposed to be aware of so that I can design on my hardrive and upload and it knows that the files are being uploaded with it?  Ugh hpe this makes sense - I'm NOT a webs designer and the new DW is way more than I use in it's technology.

    Hi
    This sounds like you have not defined your site in the site definition.
    Follow the steps in these 2 tutorials to set-up your site locally and for the remote server -
    http://www.adobe.com/devnet/dreamweaver/articles/first_website_pt1.html
    http://www.adobe.com/devnet/dreamweaver/articles/first_website_pt6.html
    PZ

  • How can I Change data in a type def control containing a Xcontrol with a local variable

    Hello
    I made a Xcontrol and I inserted this control in a type def.
    When I want to change the control's data with a local variable in a VI, the VI change nothing. The change of data isn't perform
    How can I correct this issue?
    Thanks for your help
    Solved!
    Go to Solution.

    Hello,
    What's your LabVIEW version ? Do you have a simple example program which demonstrates this behavior ?
    I found another discussions related to your issues with Xcontrols:
    updating type defs in Xcontrol Facade
    No Data Change event generated for a XControl in a Type Def
    XControl facede.vi 
    Hope this helps.
    Regards, 
    Steve M.
    National Instruments France
    #adMrkt{text-align: center;font-size:11px; font-weight: bold;} #adMrkt a {text-decoration: none;} #adMrkt a:hover{font-size: 9px;} #adMrkt a span{display: none;} #adMrkt a:hover span{display: block;}
    >> Vidéo-t'chats de l'été : présentations techniques et ingénieurs pour répondre à vos questions

  • How many ways to read and write a local variable in a called VI?

    Ciao!
    I'm producing my first TestStand sequence. It is called "FirstAttempt" and it is made by a single step which calls a VI. One of the first dilemmas i encountered realizing this sequence is how to read and write a local variable (created going in Variables -> Locals ('FirstAttempt') -> <right click to insert local>) in the called VI.
    The first way (the only one i tried) is to create a control and an indicator on the VI front panel, connect them to their respective terminals in the connector pane and then specify (going in Step Settings -> Module) that these connectors (shown in the Parameter Name column) are linked to the local variable (selected in the Value column).
    The second way (not tried) consists in using TestStand API: create a Sequence Context reference on the VI front panel, link it to a property node in the block diagram, select the property "Locals" and extract from this the local variable name and value which, i think, can be readable and writable.
    So...
    Are the shown ways correct?
    Are there other ways?
    Knowing that a "local" variable can be considered "global" within the whole sequence, is there the possibility to simply create a reference to the local variable and use the reference in the called VI block diagram in order to save space in the connector pane (if using method 1) or in the block diagram (if using method 2)?
    Thanks!
    Message Edited by aRCo on 09-17-2009 05:09 AM

    Hi,
    Before TestStand 3 you would use the second way you quoted as its the only way.
    But now you would use the first way you quoted. You may still what to pass the SequenceContext if you were going to use the TestStand API. For TestStand 3.x and above you would use this way as the first chose. (Personnelly, I would not pass the SequenceContext into a VI if I know it was never going to be used in that VI.)
    Not sure I understand your final comment, maybe you are liking it to passing the reference of a control to a subVI so that the control can be updated from within the subVI.
    If this is the case and you had a situation where you had a step that was running in parallel with the rest of the steps in the sequence either as a separate thread or execution and were dependent on the contents of the  local variable changing from that parallel running step, then you would have to use the API SetVal method to change the local.
    Hope this is clear.
    Regards
    Ray Farmer
    Regards
    Ray Farmer

  • RE: local variable cross-talk?

    Jeff
    A global can be considered as a variable to the entire code, where lots of
    different vi's can operate it. Locals only have any meaning within their
    own vi, or instances of their own vi.
    If anything writes to a particular global, whether in reenterent vi's or
    not, it's available everywhere in the code.
    What you were asking was about locals though. If a vi is non-renentrant
    (i.e. as they come out of the box) then the values in the locals are vi
    specific, no matter where the vi is, where it was last used, it retains the
    data from it's last operation. If it is re-entrant, then the values in the
    locals for each occurance of the vi are its own for EACH instance, i.e. just
    like different locals in different vi's, it doesn't matter where else the vi
    is used, the data held is that from the last operation of that specific
    instance.
    Simple way to demonstrate this. Make a vi that has one numeric control,
    then code in +1 and get it to write to a local variable for that control.
    Throw in an indicator to wire out the result of what is written to the local
    for the control.
    Then take this vi, put it in a for loop, then put another copy in the for
    loop as well. Wire the indicators to the side of the for loop and create
    indicator arrays for them. Get the loop to run 6 times say. Now try
    running this with the vi in the for loop non-reentrant and then reenterrant.
    One way the arrays will contain either all the odd no.s 1,3,5,7,9,11 and
    then the other array 2,4,6,8,10,12 (don't know which array will be which,
    depends which executes first in the for loop of this example). The other
    way they will both be 1,2,3,4,5,6. In the first example, the same vi has
    run 12 times, i.e. one copy of the vi which retains its info and is called
    in many places and therefore only has one set of values, and the other with
    two re-enterant copies where they have their information specific to that
    instance of them i.e. effectively they are different vi's. Both ways are
    useful, depends what you want.
    If you're looking for a use for non-reenterant vi's then consider this:-
    For instance. Supposing you get many things to try to write to a global
    array of numbers, and you have two vi's one "A" writes to the first element
    in the array and the other "B" writes to the second element. Because in LV
    you have to read a global first and then write to it to perform a change,
    these independant vi's "A" and "B" (be they re-enterant versions of the same
    vi, or different vi's), can be performing the tasks simultaneously in the
    code. I.e. "A" reads, "B" reads, "A" writes, and "B" writes over the top
    with a modified version of what it read, and "A"'s changes are lost. This
    is what's known as a "race condition" as "A" hadn't finished and "B" needed
    to know what "A" was going to write before "B" performed "A" read. Try it,
    hours of fun if you code this kind of thing in inadvertantly!
    If the same vi is used, and is not re enterant, it can only run in one
    instance at a time, hence two read / write operations cannot be performed
    together, problem solved. Unless that gives you timing issues of course,
    waiting for one to finish, to write the other......but that's another whole
    can of worms.
    cheers
    Tim Price
    This e-mail, its content and any files transmitted with it are intended
    solely for the addressee(s) and are confidential and may be legally
    privileged. Access by any other party is unauthorised without the express
    prior written permission of the sender. If you have received this e-mail in
    error you may not copy, disclose to any third party or use the contents,
    attachments or information in any way.
    -----Original Message-----
    From: [email protected]
    [mailto:[email protected]]On Behalf Of Jeffrey W Percival
    Sent: 29 November 2001 21:12
    To: [email protected]
    Subject: Re: local variable cross-talk?
    Another useful reply! What a great news group this is.
    One last thing I wanted to ask about, though, is global vs. local. I see
    you talk about globals, but in fact the variables in my subVI's were locals.
    I can easily understand the behavior I observed accompanying the use of
    global variables, But I guess the use of the word "local" stumped me.
    Should I interpret "local" in LabVIEW's sense to mean "local to all
    instances of this VI"? And global to mean "visible to all instances of this
    VI as well as other VI's"?
    -Jeff
    Tim Price wrote:
    This facility is actually very useful, for instances where you want to
    encapsulate some code so that it can only run in one place at a time,
    i.e.
    global arrays that are written to in more than one place. This method
    can
    eradicate race conditions completely for example when used like this.
    There
    are multiple other uses as well.
    However, using a vi as a module of code, to run in more than one
    instance at
    a time simultaneously, re-entrant is the way to go. Just make sure you
    debug it first!!!
    Remember though, just because a vi may be re-eneterant, doesn't mean
    that
    everything inside is; sub-vi's, Globals etc. The classic one I've seen
    is
    where people think that a re-enterant vi is talking to it's own copy of
    any
    Globals used within it, i.e. counters etc., where in actual fact of
    course,
    they are all using the same Globals.
    Worth playing with a few examples to get familiar with it.
    Tim Price
    Jeffrey W Percival, Senior Scientist and Associate Director
    Space Astronomy Laboratory, University of Wisconsin - Madison
    1150 University Ave, Madison, WI 53706 USA
    608-262-8686 (fax 608-263-0361) [email protected]
    http://www.sal.wisc.edu/~jwp

    Tim Price wrote:
    Tim, thanks very much. I'll try the experiment you suggest.
    Thanks for taking the time.
    -Jeff
    Jeffrey W Percival, Senior Scientist and Associate Director
    Space Astronomy Laboratory, University of Wisconsin - Madison
    1150 University Ave, Madison, WI 53706 USA
    608-262-8686 (fax 608-263-0361) [email protected] http://www.sal.wisc.edu/~jwp

  • Local variable problem

    I am making an application that takes an apartment number and number of occupants in that apartment and then displays a number of statistics. So far I haven't had much problem
    except on a what is probably a very simple problem.
    I have two buttons, and when "store" is clicked the info in the textboxes is input to an array.
    My problem is with the next button, "quit", this is where all the info is supposed to be displayed.
    All my variables that I need from "store" are local and are recognized in " the if statement in quit. Ive tried declaring them outside of the if statement, but it hasn't been working.
    {code}
    public void actionPerformed(ActionEvent event)
                   Object source = event.getSource();
                   Apartment input;
                   if (source == store)
                        Integer aptNo = Integer.parseInt(input1.getText());
                        Integer occup = Integer.parseInt(input2.getText());
                        input = new Apartment(aptNo, occup);
                        if(aptNo > BUILDING_SIZE)
                             JOptionPane.showMessageDialog(null, "That apartment number doesn't exist.");
                        else if(occup > MAX_OCCUPANTS)
                             JOptionPane.showMessageDialog(null, "Too many occupants, only 20 are permitted per apartment.");
                        else
                             occupants[aptNo] = occup;
                             input1.setText("");
                             input2.setText("");
                             JOptionPane.showMessageDialog(null, input.getNumber(occupants));
                   if (source == quit)
                   // I need the variables aptNo and occup in here to put into my methods for output, but I don't know how to get them.     
    {code}

    EmmCeeVee wrote:
    Thank you for all of the responses, it really helps me out.
    Obviously my knowledge of local variables is hurting as I switched it around as your said and declared the aptNo and occup outside of the if's.
    All I need is for the quit button to look at the array ( which has just been modified by the sotre button) and output a bunch of results.
    Heres where im at:Your problem is of scope of the variables.
    Here whatever variable you defined in actionPerformed they are local for that method (they are out of scope when the method is finished/called again), Upon this, the actionPerformed is called twice one for store and another time for quit. So you cant expect the value stored at store should be there still when you all quit
    If you want those values available on both the actions then make them a class level variables.
    Below is a sample program, might help you.
    class Employee
         String empName = null;
         int empNo;
         Employee(String eName,int eNmbr)
              this.empName = eName;
              this.empNo = eNmbr;
    class CheckVariableScope
            Employee empOb; // Here
         int eNo;
         String eName = null;
         public void checkScope(String action)
                    //Instead of defining Employee reference variable, eNo and eName  in checkScope method, define it @ class level.
                    // in your case they are Apartment input, Integer aptNo and Integer occup
                     // like above i did.
                     // If i comment the class level variable and uncomment method variable, this program also give the same error.
              //Employee empOb;
              //int eNo;             
              //String eName = null;
              if (action.equals("Store") )
                        eNo = 10;
                        eName = "Bob";
                        empOb = new Employee(eName, eNo);
                        System.out.println("The eName is : "+empOb.empName+" , empNo is : "+empOb.empNo);
                   if (action.equals("quit"))
                        System.out.println(" eNO from Object is : "+empOb.empNo);
                        System.out.println(eNo); //Error: may not have been intitialized
         public static void main (String st[])
              CheckVariableScope ob = new CheckVariableScope();
              ob.checkScope("Store");
              ob.checkScope("quit");
    }

Maybe you are looking for

  • Configuration error - please uninstall and reinstall the product

    Configuration error - please uninstall and reinstall the product - Installieren lässt sich Indesign jedoch nicht Da frage ich mich, was zu tun ist thank you

  • How do read the data of the excel file line by line to the waveform?

    hello:       i am a beginner.so i hope that  you can give me a small example.the data of the excel  file i  have given out. looking for your replys!!! Solved! Go to Solution. Attachments: 数据.xls ‏14 KB

  • Maverick mail, new folders

    why do I have so many new folders in mail? On my mac, there's junk (gmail), junk (icloud), junk (my pop account), plus I have a junkmail folder in each account folder, there's a deleted message folder in each account, and then there's also trash in e

  • Where to find docs for JVM parameters for JDK 1.4?

    Can somebody tell me where to find a complete documentation for JVM parameters for jdk 1.4? Thanks in advance

  • Oracle Client 10 Unattended Installation

    Hello, using the unattended installation mode: steup -nowait -force -silent -responseFile c:\test.rsp the installation failes. the errorlog tells me that DepMode and TLDepmode is not defines in the answer file. The test.rsp was recorded by using the