Reputation: 243
I have some super simple code but I'm pulling my hair out. I'm just trying to have AskQuestion() return after the user gives one input but I don't understand why this java code requires 2 inputs before returning. Originally, I was trying to solve this problem with a while loop, but I've deleted everything and found what I think the root problem is -- that a return only happens after a second input, but I cannot figure out why.
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
I don't think this affects this, but here's how I'm calling AskQuestion () from another file.
if (input.equals("1")) {
RelationalQuestion q1 = new RelationalQuestion (animalArray, answer);
q1.AskQuestion();
if (q1.AskQuestion() == false) {
questionsLeft++; //neutalize decrement of questions if returned false
}
}
Upvotes: 0
Views: 149
Reputation: 72
Your program is showing two times the question due your code is calling AskQuestion() function twice.
q1.AskQuestion(); //call the first time the function
if (q1.AskQuestion() == false ) //call the second time the function
What I suggest is store the result into a new variable and compare after that.
Boolean result = q1.AskQuestion();
if(!result) { //.....// }
OR
Just delete the first call.
Upvotes: 2
Reputation: 909
q1.AskQuestion(); if (q1.AskQuestion() == false) {
You are calling AskQuestion twice in a row. You should probably get rid of the first one.
Upvotes: 2