Reputation: 157
I am basically playing around with eclipse to retain what I learned in my intro to Java class. I am about to enroll in advanced programming and I have a beginner's question...
I created this little program below because I was having a hard time understanding methods. Now that I have the general concept down, I have a new question. I have a do while statement below and it works if you enter the right answer to the simple addition problem. If you enter the wrong answer, it will ask you to try the problem again (as I want it to). If you enter the wrong answer again, the program stops. I want it to prompt the user to enter the answer until they're correct. How do I do this?
import java.util.Scanner; //needed for input
public class PracticeMethod {
public static void main(String[] args) {
// Create a Scanner
System.out.println(");
System.out.println();
makesPerfect();
String anotherRun = "yes";
Scanner input = new Scanner(System.in);
}
static void makesPerfect() {
Scanner input = new Scanner(System.in);
String anotherRun;
do {
System.out.print(" Math");
int x = (int) (Math.random() * 10) + 1;
int y = (int) (Math.random() * 10) + 1;
System.out.print(" What is " + x + "+" + y + "? ");
double answer = 0.0;
answer = input.nextDouble();
if (answer == x + y) {
System.out.println(" Yes, you are correct.");
}
if (answer != x + y) {
System.out.print(" No, that is not correct. ");
System.out.println();
System.out.print(" Why dont you try again? ");
System.out.println();
System.out.println();
System.out.print(" What is " + x + "+" + y + "? ");
answer = input.nextDouble();
}
System.out.println();
System.out.print("Enter yes if you want to run again: ");
anotherRun = input.next();
input.nextLine(); // causes skipping issue to fix
System.out.print("\n\n\n");
} while (anotherRun.equalsIgnoreCase("yes"));
}
}
Upvotes: 0
Views: 5248
Reputation: 11006
Make your if
statement checking if the answer is correct a while
loop. That way you'll just keep asking for the correct answer until you get it.
while(answer != x + y) {
System.out.print(" No, that is not correct. ");
System.out.println();
System.out.print(" Why dont you try again? ");
System.out.println();
System.out.println();
System.out.print(" What is " + x + "+" + y + "? ");
answer = input.nextDouble();
}
Also kudos for using StackOverflow correctly, and for making an effort to learn! One day maybe you'll be answering questions for me.
Upvotes: 3