scan.next()在循环中不起作用

时间:2023-02-04 21:52:33

I'm working on a program to play the game of Go Fish. Everything works except for the scan.next() after looping through once.

我正在制作一个玩Go Fish游戏的程序。循环一次之后,除了scan.next()之外的一切都有效。

Well, sometimes it works and sometimes it doesn't. Here's the code:

嗯,有时它有效,有时则不然。这是代码:

System.out.println(compHand.showHand());       

while (!(deck.isEmpty())) {
    y = 0;

    while (x == 1) {             

        System.out.println("\nYour hand:" + userHand.showHand()+ "\nYour turn. What number do you want to match?");
        guess = scan.next();
        if (compHand.checkHand(guess)) {
            System.out.println("Darn...here you go.");
            userHand.removeNum(guess);
            compHand.removeNum(guess);
            userHand.showHand();
            uP++;
        }
        else {
            System.out.println("Nope! Type '1' to go fish!");
            y = scan.nextInt();
            if (y == 1) {
                userHand.goFish();
                System.out.println(userHand.showHand()); 
            }
            y = 0;
        }

        guess = "";
        x--;
    }

    while (x == 0) {
        System.out.println("Do you have any " + compHand.ask() + "s?");
        ans = scan.next();
            if (!(ans.contains("go"))) {
                System.out.println("Yay!");
                userHand.removeNum(ans);
                compHand.removeNum(ans);
                cP++;
                x++;
            }
            else {
                System.out.println("Aww...darn.");
                compHand.goFish();
                x++;
            }
        }

        System.out.println("Computer's points so far: " + cP + "\nYour points so far: " + uP + "\n");
    }        
}

So the first time it loops through to do the user's hand, it works. Then it works for the computer's turn, but if the computer has to go fish. When it loops back up to the user's hand it skips the guess = scan.next();. I don't know what to do...

因此,第一次循环来完成用户的操作时,它可以工作。然后它适用于计算机,但如果计算机必须去钓鱼。当它循环回到用户手上时,它会跳过guess = scan.next();.我不知道该怎么办...

1 个解决方案

#1


-1  

The problems comes from the buffer. You have to free it. To do so, put a scan.nextLine() just before the closing bracket of the loop and it will free the buffer. You will be able then to enter an input.

问题来自缓冲区。你必须释放它。为此,将一个scan.nextLine()放在循环的右括号之前,它将释放缓冲区。然后,您就可以输入输入。

#1


-1  

The problems comes from the buffer. You have to free it. To do so, put a scan.nextLine() just before the closing bracket of the loop and it will free the buffer. You will be able then to enter an input.

问题来自缓冲区。你必须释放它。为此,将一个scan.nextLine()放在循环的右括号之前,它将释放缓冲区。然后,您就可以输入输入。