2

I am getting a compiling error for this code:

public class Matching {        
    public static int match = (int) Math.floor(Math.random()*cities.size()); //Error is here
}

I'm want to make "match" a global variable.

My compiling error is:

"Illegal static declaration in inner class testingProgram.Matching modifier 'static' is only allowed in constant variable declarations

Usage of static non-final variable during initialization."

Don't know what the error means, nor do I know how to fix it.

3
  • If you don't plan to change the variable, add the final keyword before or after static. Commented Jun 10, 2017 at 12:34
  • 1
    What is cities variable? Your code is not clear, and it is not possible to test it. Commented Jun 10, 2017 at 12:38
  • cities is an arraylist Commented Jun 10, 2017 at 12:38

2 Answers 2

2

This happens because your Matching class is located inside another class called testingProgram, and is not static.

Java allows static fields inside an inner class only when the inner class itself is static. You can fix this problem in several ways:

  • By making Matching a static inner class,
  • By making Matching a top-level class, or
  • By making static int match final, i.e. final static int match
Sign up to request clarification or add additional context in comments.

1 Comment

How do you know it is an inner class?
0

Create the variable in some static class (main, for example) and make sure it gets passed to the constructor of this class. I don't know why you are doing this but the reason it's difficult is because it's not a good idea. If you need to save the state of 'match' then give more information.

public static void main() {
    int match;
    Matching m = new Matching(match);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.