Carl Kim
Carl Kim

Reputation: 43

Why is my method running twice?

When I tried to make my own class with my own method, the method was running twice. I tried turning parts of the code to find the glitch, but the method was still running twice.

Here is the class:

import java.util.Scanner;

public class TestRB
{
    private String userInput;
    private Scanner scan = new Scanner (System.in);

    public TestRB ()
    {
        run();
    }

    public void run ()
    {
        System.out.println("Please input y or n.");
        userInput = (scan.next()).toLowerCase();
        while (!userInput.equals("y") && !userInput.equals("n"))
        {
            System.out.println("Invalid input, try again.");
            System.out.println("Please type in \"y\" or \"n.\"");
            userInput = (scan.next()).toLowerCase();
        }
    }

    public boolean yOrN ()
    {
        return (userInput == "y");
    }

    public String toString()
    {
        return userInput;
    }
}

And here is the object of the method.

public class TestRunRB
{
    public static void main (String[] args)
    {
        TestRB test = new TestRB();
        test.run();

        if (test.yOrN())
            System.out.println("Yes");
        else
          System.out.println("No");
    }
}

The output is always No after I get prompted twice, regardless of whether I inputted y or n.

Upvotes: 4

Views: 4199

Answers (2)

Balwinder Singh
Balwinder Singh

Reputation: 2282

Two Problems are there.

1) The run() method is being called twice because it first runs in constructor when you call

TestRB test = new TestRB();

and then again call it again explicitly

test.run();

2) The second issue is related to printing output as No even though you entered y The reason for this is because you are not using equals method for string evaluation. You should change your existing yOrN method to following

public boolean yOrN ()
  {
    return (userInput.equals("y"));
  }

Hope this helps

Upvotes: 1

Ryan
Ryan

Reputation: 1974

You are calling test.run() in your constructor for class TestRB. You can either remove that call in the constructor or remove the method call

test.run(); 

from class TestRunRB. You are just effectively calling that method twice.

Upvotes: 4

Related Questions