-3

For my own Logger class I want to define a map to map the priority number back to a meaningful string like follows:

static Map<int, String> map = new HashMap<int, String>();
map.put(2, "VERBOSE");
map.put(3, "DEBUG");
map.put(4, "INFO");
map.put(5, "WARN");
map.put(6, "ERROR");

I wonder if there might be a function that does this automatically? But I do now know every function there is.

However, I define the lines just before my class definition, and then I get the error:

Error:(14, 8) error: class, interface, or enum expected

and not sure what it means (maybe I cannot declare variables outside a class?). I also tried to define the map inside the class, but then the put method cannot be resolved. I also notice, that I have not imported a Map module, and AndroidStudio does not seem to require a Map module (i.e. the name 'Map' is not red and underlined).

I am very confused (as usual); I just want to get a String "ERROR" if the priority-value is 6 and so on.

What am I doing wrong in my case...?

Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

3

maybe I cannot declare variables outside a class?

Correct.

Use:

class Foo {
  static Map<Integer, String> PRIORITY_LABELS = new HashMap<>();

  static {
    PRIORITY_LABELS.put(2, "VERBOSE");
    PRIORITY_LABELS.put(3, "DEBUG");
    PRIORITY_LABELS.put(4, "INFO");
    PRIORITY_LABELS.put(5, "WARN");
    PRIORITY_LABELS.put(6, "ERROR");
  }

  // rest of class goes here
}

I also notice, that I have not imported a Map module, and AndroidStudio does not seem to require a Map module (i.e. the name 'Map' is not red and underlined).

That is because Android Studio does not know what to do with that code. Once you move them into the class, then Android Studio will realize that you are trying to use Map and HashMap and will ask you to import them.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I had `Map` and `HashMap` inside the class, and android did not ask to import anything. Anyway, your solution seems to work... – Alex Sep 19 '16 at 19:12
  • @Alex: Perhaps you have `import java.util.*;` or something that bulk-imports a bunch of classes and interfaces, including `Map` and `HashMap`. – CommonsWare Sep 19 '16 at 19:18
  • @CommonsWare hello sir, Sorry to comment in between please I need a logic to this question http://stackoverflow.com/questions/39576258/how-to-keep-user-logged-in-always-connected-with-server –  Sep 20 '16 at 07:00
  • It can be an encoding problem. check this: https://stackoverflow.com/questions/31665663/android-studio-error-class-interface-or-enum-expeted/53350503#53350503 – c-an Nov 17 '18 at 10:58