-3

I'm working on my first Android app coming from 2 years of C++ from school.

The code looks like this:

double total = 100000000000L;
for(long i = 0L; i < diff; i++) {
    total += 1.8;
}
countView.setText(NumberFormat.getInstance().format(total));

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
     @Override
     public void run() {

         if (total += 1.8 < 200000000000L) {
            handler.postDelayed(this, 1000L);
            return;
         }

         handler.removeCallbacks(this);
     }
 }, 1000L);

In C++, I'd be able to reuse the total variable no problem - it's in the same scope. But in Java I'm getting an error message that I'm attempting to access an inner class. Trying to declare total as public or static gives the error that the modifier isn't allowed here.

Why can I use total right below where I declare but not several lines down?

FutureShocked
  • 779
  • 1
  • 10
  • 26
  • 1
    Where exactly is your `total` several lines down? Have you not included that? – Codebender Jul 08 '15 at 08:50
  • https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html ... of course `total` could be a field in outer class and everything should be ok .. edit: and yeah, as @Codebender wrote we don know where you declar `total` in method? or as a field (of course not, but this is only assumption) – Selvin Jul 08 '15 at 08:51
  • total is declared at the top and used in an if statement in the run function – FutureShocked Jul 08 '15 at 08:53
  • Check this answer http://stackoverflow.com/questions/18225572/use-of-final-local-variables-in-java – Gordak Jul 08 '15 at 09:05

2 Answers2

1

In Java, if you want to access members of the enclosing class (i.e. total in your example) from a local class like the Runnable in your example, these members have to be declared as final.

https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

For your code, instead of having double total, rewrite the code (if you can) so that total becomes an integer and use final AtomicInteger total. If you cannot rewrite, I would look into AtomicDouble alternatives.

Community
  • 1
  • 1
reikje
  • 2,850
  • 2
  • 24
  • 44
0

If total is a class field in which your handler is called it should work without any problems. If it is declared inside a function which calls your handler, try declaring it as "final". The only problem is that by declaring it as final, you won't be able to modify it's value, as you do so inside the run() method.

  • total is just a primitive data type, declared at the top of the code block. Does java treat primitive data types as classes, and if so why can I use it during my for loop but not in a function? – FutureShocked Jul 08 '15 at 08:56