1

This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input. Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.

public static void main(String[] args) {

    boolean quizActive = true;
    while(quizActive) {

        presentQuestion();
        presentAnswers();

        Scanner s = new Scanner(System.in);

        if (s.hasNext()) {
            String choice = s.next();

            if (!NumberUtils.isNumber(choice)) {
                presentText("Please insert the answer number.");
            } else {
                System.out.println("You made a choice!");
                checkAnswer(choice);
                quizActive = false;
            }
            s.close();
        }
    }
}

What am I doing wrong here?

0

4 Answers 4

3

If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.

But main problem is that you closing Scanner.

Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.

Sign up to request clarification or add additional context in comments.

6 Comments

Actually, is hasNext works with System.in ? I don't even think this is entering the condition block that close the Scanner because this would try to recreate a Scanner with a closed InputStream (System.in) closed by the Scanner, giving an exception a believe.
The reason presentQuestion() and presentAnswers() are inside the loop is because (in a later stage) I want to have a varying amount of questions. So calling the same methods will deliver different questions. Therefore, I need to call them again until quizActive is no longer true (which would get deactivated at the end of the whole quiz, rather than at the end of the question).
@AxelH Yes. I debugged it. First time it blocks on hasNext but after scaner is closed its underlying stream is closed too. After that hasNext just return false without blocking.
@KeizerHarm then you need two loop. First for questions and second for retry if answer is not number. I suggest you to create quiz with only one question and after it works properly extend your program to handle multiple questions.
@talex, hmm, so what should then be the condition of the inner loop? Something already there, like hasNext(), or should I make a new boolean questionActive for the purpose?
|
2

I really don't get the point in using scanner for acquiring user input.

The scanner class is perfect to process structured input from a flat file with known structure like an CSV.

But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...

So why not using InputStreamReader aside with a loop suggested by others?

13 Comments

To be honest, I am using Scanner here to make my life easier, so I can test it all with the console, until I figure out what sort of UI I want to put in front of it (one that accepts both numbers and commands, ideally).
@KeizerHarm "I am using Scanner here to make my life easier" if it was easier, why do you have to ask this question? ;o)
Well, making the actual UI (which I have little experience with) would probably lead to even more debugging, so I might as well start with something I sorta know how to use...
@KeizerHarm "Well, making the actual UI" why do you consider command line not being an UI? And why do you think Scanner is the only possible solution for command lines?
Because Scanner is the only one they taught me in the tutorial, and I didn't consider the existence of anything else with the same function. But I suppose I should now just Google InputStreamReader and figure out what that is...
|
1

Here an Example :

  public class Application {
  public static void main(String [] args) {

    System.out.println("Please insert the answer number. ");

         while (true) {
            try {
                Scanner in = new Scanner(System.in);
                int choice = in.nextInt();
                System.out.println("You made a choice!");
                checkAnswer(choice);


                break;
            } catch (Exception e) {
                System.out.println("Invalid Number, Please insert the answer number ");
            }


        }
    }
}

Comments

1

You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.

If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().

To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!

if you want a code example, please tell me :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.