-6

Whenever i create a goblin object and call the method isNice, it always return false. But when i do System.out.println(nice) it does it randomly.

public class Goblin
{

    private boolean nice;
    private boolean isNice;


    public Goblin()
    {
        // initialise instance variables
          Random rand = new Random();
         boolean nice = rand.nextBoolean();

    }

    public boolean isNice()
    {

            return true;

        else 
            return false;
    }

}

Marius Kuzm
  • 159
  • 1
  • 9
  • 1
    First, just return the boolean: `isNice() { return isNice; }` – markspace Oct 30 '18 at 21:41
  • 1
    Because you don't assign the result of `rand.nextBoolean()` to `nice` but to a local variable. – khachik Oct 30 '18 at 21:42
  • 1
    You are setting a local variable instead of a class property. As a solution try `this.nice = rand.nextBoolean();` – gusto2 Oct 30 '18 at 21:43
  • 1
    `isNice` can be simplified to `return nice;`. – Andy Turner Oct 30 '18 at 21:45
  • The `boolean nice` in the constructor declares a *local variable* that is **shadowing** the *field* `nice`, so you're not setting the value of the field anywhere. See [What are Shadow Variables in Java?](https://stackoverflow.com/q/26297180/5221149) – Andreas Oct 30 '18 at 21:45
  • Maybe, you output isNice variable (which by default initialized to false), not isNice() method? – Oleksii Morenets Oct 30 '18 at 21:47

1 Answers1

3
boolean nice = rand.nextBoolean();

is declaring and assigning a local variable. You aren't assigning the field, so it will always have its default value, false, when you access it with the getter.

Drop the boolean.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • To explain further: Since you didn't assign `nice` to true- `nice` will never equal true and thus the method `isNice()` always returns false. – chevybow Oct 30 '18 at 21:44