Joe Mckinstry Joe Mckinstry - 3 months ago 14
Java Question

How to do goto in Java?

I'm trying to make a game like family feud where the user gets asked a question and they have to reply 3 times so I was wondering if there was something like

goto
that I could use.

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

Answer

You're overthinking this, a for loop is all you need:

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 in any language is bad practice, as it makes it difficult to follow the code. There is practically always a better way of accomplishing what you want.

Comments