如何在Java中转到goto?

时间:2016-08-18 04:25:48

标签: java

我试图制作一个像家庭不和的游戏,用户会被问到一个问题而且他们必须回复3次,所以我想知道是否有类似goto的东西我可以使用。< / p>

Question question = questions.get(new Random().nextInt(questions.size()));
System.out.println(question.getQuestion());
Scanner scanner = new Scanner(System.in);

//want to put start right here but can't
//start:

String answer = scanner.nextLine();

for (Answer a : question.getAnswers())
{
    if (a.getAnswer().toLowerCase().contains(answer))
    {
        System.out.println(a.getAnswer() + " " + a.getPoints());
        return;
        //Make it go back to start right here
    }
}

System.out.println("WRONG!");
//also make it go back to start right here

3 个答案:

答案 0 :(得分:2)

您不需要goto。更好的方法是使用break并在循环后检查结果:

Question question = questions.get(new Random().nextInt(questions.size()));
System.out.println(question.getQuestion());
bool success = false;
Scanner scanner = new Scanner(System.in);

for (int i = 0; i < 3 && !success; i++) {
    String answer = scanner.nextLine();
    for (Answer a : question.getAnswers()) {
        if (a.getAnswer().toLowerCase().contains(answer)) {
            System.out.println(a.getAnswer() + " " + a.getPoints());
            success = true;
            break;
        }
    }
}

if (!success) {
    System.out.println("WRONG!");
}

答案 1 :(得分:1)

你过度思考这个问题,你需要for循环:

Question question = questions.get(new Random().nextInt(questions.size()));

System.out.println(question.getQuestion());

Scanner scanner = new Scanner(System.in);

for (int i = 0; i < 3; i++) {
    String answer = scanner.nextLine();

    boolean correct = false;
    for (Answer a : question.getAnswers()) {
        if (a.getAnswer().toLowerCase().contains(answer)) {
            System.out.println(a.getAnswer() + " " + a.getPoints());
            correct = true;
            break;
        }
    }
    if (!correct) {
        System.out.println("WRONG!");
    }
}
任何语言中的

goto都是不好的做法,因为它很难遵循代码。实际上总有一种更好的方法来实现你想要的东西。

答案 2 :(得分:-1)

尝试围绕此代码进行简单的while循环,如下所示:

String answer = scanner.nextLine();

while (true)
{
    for (Answer a : question.getAnswers())
    {
        if (a.getAnswer().toLowerCase().contains(answer))
        {
            System.out.println(a.getAnswer() + " " + a.getPoints());
        }
        else
            break; // exit the loop if IF statement is false.
    }
    System.out.println("WRONG!");
    break;
}