4

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.

Carl Kim
  • 43
  • 1
  • 4
  • 8
    `run()` is being run twice because you are calling it twice. Once in the constructor, and then once right after construction. Also, you are always getting "no" because of this: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – gla3dr Oct 20 '15 at 22:56
  • Ah, thank you! I got it now. So I don't need the `run();` there? An example that I had did, so I just put it there. – Carl Kim Oct 20 '15 at 23:01

2 Answers2

4

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.

Ryan
  • 1,972
  • 2
  • 23
  • 36
  • Oh, so if I remove the first method in my classes the program won't be prompted twice? – Carl Kim Oct 20 '15 at 23:11
  • you can either remove the call in your main method in TestRunRB or the call in your constructor for TestRB on what appears to be line 10. – Ryan Oct 20 '15 at 23:12
1

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

Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34