Question

I am writing an incredibly primitive blackjack game for a high school programming class and I am playing with writing a boolean as such:

public boolean DealerTracker()
 {
  if(a==11 || a==12|| a==13)
  {
     a = 10;
  }
  dealerHandValue = a + dealerHandValue;
  if(dealerHandValue>21)
  {
     DealerHand.setText("The House went bust!! Everybody wins!!");
     return true;
  }
  else if(dealerHandValue<21)
  {
     return null;
  }

  else if(dealerHandValue==21)
  {
     return false;
  }

 }   

I keep getting an error saying that return null (I couldn't manage to get the fancy blockquote to work) is invalid. However, for this boolean to work I really need three return statements. So my question is this: Is there a way to make null work, or is there something I can put in its place that is still usuable, or am I just being stupid here.

Please note that I do not really need this boolean, so if you think that there is no solution, just advise deletion of the boolean.

Was it helpful?

Solution 2

boolean primitives cannot be null. You basically have two options I can see:

Have your function return a Boolean (note the capital 'B'). Boolean is an object, rather than a primitive, and so can be null.

A better solution would be to define an enum. That helps you preserve the semantic meaning of the return value, which will make your code more readable and easier to maintain.

OTHER TIPS

Primitives booleans can only return values true or false. You need to return the Object wrapper type for boolean

public Boolean dealerTracker() {
 ...

If you don't really need the boolean, make the return type void and remove all return statements. If you do need boolean AND null, change the return type to Boolean, which will return a boolean wrapped in an object that can actually be null. The method that calls this method can then receive a true, false, or null, since null actually represents something too (although I'm not sure in this case it represents anything meaningful).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top