質問

thanks for reading this. I'm creating just a simple, generic version of blackjack using java. Everything else works completely fine, except when it asks you "hit or pass" and you type pass, you must type it twice for it to reconize it, and I cant seem to find out why. Heres my code on pastebin to make it easier to read: http://pastebin.com/GF7Rzusx

Relevant code from pastebin:

  public void ask()
    {
        System.out.println("Hit or Pass?");
        if (in.next().equalsIgnoreCase("Hit"))
        {
            hit();
        }
        if (in.next().equalsIgnoreCase("Pass"))
        {
            pass();
        }
    }
役に立ちましたか?

解決

If the entered word is "Pass" it is read from standard input and then lost, it is not stored. It must be stored for it to be available again in the subsequent check:

String input = in.next();

if (input.equalsIgnoreCase("Hit"))
{
    hit();
}
else if (input.equalsIgnoreCase("Pass"))
{
    pass();
}

他のヒント

Surely you want:

public void ask()
{
    System.out.println("Hit or Pass?");
    String answer = in.next();
    if (answer.equalsIgnoreCase("Hit"))
    {
        hit();
    } else if (answer.equalsIgnoreCase("Pass"))
    {
        pass();
    }
}

Each time you call in.next() it throws away the previous input and expects another token (input).

Example

Imagine what would happen if you had:

System.out.println(in.next());
System.out.println(in.next());

What would it expect as input and what would it output?

Main differences in code

Note that there are two differences in the new code:

  1. You only call in.next() once and so only need one input, which is stored as answer.
  2. You only check whether the answer is "Pass" if it wasn't already "Hit".

See Java Scanner.next documentation.

On row 112 you do:

in.next()

This will read one string token. So if you write pass, this function will return "pass".

The problem is that you do not save this value. Instead, you run in.next() again on row 116, which will require you to write pass yet again.

Instead you would like to store the string returned from in.next() on line 112.

It is because of the way the ask() method is structured. Since you have two if statements, in.next() gets called once when checking if the response is "hit", then a second time when checking for "pass". When you enter "pass", the first if statement calls next(), which returns "pass" and checks if that is equal to "hit", then moves on. Then when the second if statement calls next(), there is no next entry to return, so you have to enter "pass" again. This works when you enter "hit", however, since that is the first case checked.

Refactoring so ask only makes one call to next() should solve the problem.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top