扫描仪需要两个输入才能返回

时间:2018-11-30 04:56:17

标签: java while-loop java.util.scanner

我有一些超级简单的代码,但是我正在拔头发。我只是想在用户提供一个输入之后让AskQuestion()返回,但是我不明白为什么这个Java代码在返回之前需要2个输入。最初,我试图使用while循环解决此问题,但是我删除了所有内容,发现我认为根本的问题是-仅在第二次输入后才返回,但我不知道为什么。

import java.util.*;

public class RelationalQuestion extends Question {
    RelationalQuestion(Animal[] animals, Animal answer) {
        super(animals, answer);
    }

    public boolean AskQuestion() {

        Scanner q = new Scanner(System.in);
        boolean waitingForValidAnswer = true;
        boolean decideToDecrement = true;

        System.out.println("What do you want to know?");
        System.out.println("\t1. Is it heavier than another animal?");
        System.out.println("\t2. Is it taller than another animal?");
        System.out.println("\t9. Go back");

        if (q.hasNext());
            String relationalQuestionNumber = q.nextLine();

        return decideToDecrement;
    }// end AskQuestion
}// end RelationalQuestion

我认为这不会对此产生影响,但是这是我从另一个文件调用AskQuestion()的方式。

 if (input.equals("1")) {

        RelationalQuestion q1 = new RelationalQuestion (animalArray, answer);
        q1.AskQuestion();
        if (q1.AskQuestion() == false) {
        questionsLeft++; //neutalize decrement of questions if returned false
        }
    }

2 个答案:

答案 0 :(得分:2)

   q1.AskQuestion();
    if (q1.AskQuestion() == false) {

您连续两次调用AskQuestion。您可能应该摆脱第一个。

答案 1 :(得分:2)

由于您的代码两次调用了AskQuestion()函数,因此您的程序显示了两次问题。

q1.AskQuestion();                //call the first time the function
if (q1.AskQuestion() == false )  //call the second time the function

我建议将结果存储到新变量中,然后进行比较。

Boolean result = q1.AskQuestion();
if(!result) { //.....// }

OR

只需删除第一个电话即可。

相关问题