Cannot refer to a non-final variable inside an inner class defined in a different method

前端 未结 20 2726
一向
一向 2020-11-21 05:04

Edited: I need to change the values of several variables as they run several times thorugh a timer. I need to keep updating the values with every iteration through the timer

20条回答
  •  花落未央
    2020-11-21 05:48

    Good explanations for why you can't do what you're trying to do already provided. As a solution, maybe consider:

    public class foo
    {
        static class priceInfo
        {
            public double lastPrice = 0;
            public double price = 0;
            public Price priceObject = new Price ();
        }
    
        public static void main ( String args[] )
        {
    
            int period = 2000;
            int delay = 2000;
    
            final priceInfo pi = new priceInfo ();
            Timer timer = new Timer ();
    
            timer.scheduleAtFixedRate ( new TimerTask ()
            {
                public void run ()
                {
                    pi.price = pi.priceObject.getNextPrice ( pi.lastPrice );
                    System.out.println ();
                    pi.lastPrice = pi.price;
    
                }
            }, delay, period );
        }
    }
    

    Seems like probably you could do a better design than that, but the idea is that you could group the updated variables inside a class reference that doesn't change.

提交回复
热议问题