Java Scanner忽略答案

时间:2015-08-30 21:51:01

标签: java java.util.scanner

嗨,这是我的第一篇帖子,我有一个问题:

我有一个程序,在某个时刻,询问用户是否想要分享星星,如果他认为这样做,程序会回去收集它们,并在一段时间后回到问题,如果他想要再次分享。

问题在于,当用户回到那一点时,程序会忽略你给它的任何答案,然后转到“其他答案块”。

看起来像这样:

"Do you want to share your stars?

yes

Please answer with yes or no"

代码:

import java.util.Random;
import java.util.Scanner;

public class App {
static Scanner skan = new Scanner(System.in);
static int starCount = 0;
static Random random = new Random();

public static void main(String[] args) {
    starReaching();

}

static void starReaching() {
    boolean starCollected = false;
    int i = 0;
    int j = random.nextInt(101);

    while (i < j) {
        i++;
        System.out.println("Stars are out of reach");
    }
    if (i > j || i == j) {
        starCollected = true;
    }
    if (starCollected == true) {
        starCollector();
    }
}

static void starCollector() {
    System.out.println("You caught a star !");
    starCount++;
    if (starCount == 10) {
        System.out.println("You have 10 stars ! :)");
        System.out.println("Do you want to share your stars?");
        String line = skan.nextLine();
        if (line.equals("yes")) {
            skan.reset();
            starGiver();
        } else if (line.equals("no")) {
            wishMaker();
        } else {
            System.out.println("Please answer with yes or no");
            System.exit(0); 
        }
    } else {
        starReaching();
    }
}

static void starGiver() {
    System.out.println("How many do you want to share?");
    int starsToShare = skan.nextInt();
    if (starsToShare < 10 || starsToShare == 10 && starsToShare > 0) {
        starCount = starCount - starsToShare;
        System.out.println("Stars shared !");
        System.out.println("You now have " + starCount + " stars");
        System.out.println("Go collect them again!");
        starReaching();
    } else if (starsToShare > 10) {
        System.out.println("You don't have enough stars to share that much!");
        starGiver();
    } else {
        System.out.println("That's not a valid option");
        starGiver();
    }
}

static void wishMaker() {

}

}

2 个答案:

答案 0 :(得分:1)

每次拨打skan.nextLine()时,您都会读取新行并推进扫描仪的指针,这就是您的代码失败的原因:您经常调用此代码。

而不是

if (skan.nextLine().equals("yes")) {
    skan.reset();
    starGiver();
} else if (skan.nextLine().equals("no")) {
    wishMaker();
} else {

做的:

String line = scan.nextLine(); // read from Scanner **once** only
if (line.equals("yes")) {
    skan.reset();
    starGiver();
} else if (line.equals("no")) {
    wishMaker();
} else {

答案 1 :(得分:0)

好的,我发现了这个小虫子,我之后使用的是skan.nextInt而没有使用skan.nextLine,谢谢你的快速帮助,非常喜欢