-2

So im trying to make a counter and im using a switch statement

Here's the Code im trying:

 private View.OnClickListener clickListener = new View.OnClickListener() {
      @Override
      public void onClick(View view) {
          switch (PIP1) {
              case PI1:
                  Counter++
                  break;
          }
      }
  };

Its inside a button: Im getting an error "Constant expression required" at case PI1. I take PIP1 and PI1 like that from another activity:

  PIP1 = getIntent().getStringExtra("PlayerText");
  PI1 = getIntent().getStringExtra("Player1Text");
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
triple50
  • 33
  • 6
  • 1
    Please show how you declare `PI1`. – Andy Turner Aug 25 '19 at 21:44
  • I get PI1 from another activity is a String and PIP1 too. – triple50 Aug 25 '19 at 21:47
  • 1
    I didn't ask you to describe it, I asked you to *show* it. There are strict requirements on what allows a variable to be considered a constant, so the details are important. – Andy Turner Aug 25 '19 at 21:48
  • 1
    It needs to be a compile time constant. `String`s are hashed and then an integer switch over the hash code will be constructed by the compiler, with some additional checking in each case that the strings match. – Johannes Kuhn Aug 25 '19 at 21:49
  • Sorry can you give me a example i dont really know what do you mean – triple50 Aug 25 '19 at 21:50
  • 3
    I guess he wanted to see how do you declare (define) PIP1 variable. For example: `public static final String PIP1 = "pip1value";` – jpact Aug 25 '19 at 21:51
  • 1
    You can't put something that is not a constant whose value is known at compile tile into switch(). That's what the error means. And what Andy means is that you should edit your question and post the code where PIP is declared instead of vaguely describing the code. When answering a question about code, seeing the code helps a lot. Guessing it based on a description doesn't help as much. – JB Nizet Aug 25 '19 at 21:51
  • Well, if he takes it from another activity, then it cannot be a constant for sure. For further explanaition of `java` constants and `switch` block check: https://stackoverflow.com/a/3827424/3479154 – jpact Aug 25 '19 at 21:53
  • 1
    @jpact that's not true. Constants can be defined in any class. – Andy Turner Aug 25 '19 at 21:55
  • @AndyTurner obviously, thats true. I was thinking about getting it at runtime, through `Intent` extras for example. – jpact Aug 25 '19 at 21:57
  • you have only one case, why not use just an `if`? – user85421 Aug 25 '19 at 22:40

1 Answers1

0

I try what @jpact said instead of declearing them like that

 String PIP1;
 String PI1;

You just do this:

 public static final String PIP1 = "PlayerText";
 public static final String PI1 = "Player1Text"; 

Player1Text and PlayerText is the Keys.

Again thanks to @jpact

triple50
  • 33
  • 6