I've only been taking coding classes for a month, so I'm really sorry if I'm using some wrong/wacky constructions.
I'm trying to make an addition game using two random numbers; r1 determines the number of terms in the addition problem, while r2 assigns a value to each of them. The scanner checks the user's input and based on that the game either gives points or counts failed attempts.
The problem is that the first iteration runs fine, but it never displays a new problem, even though the condition of the main while loop (3 wrong answers) hasn't been met.
Could you please give me some pointers? Thanks!
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
public class AddingGame {
Random rand1, rand2;
int points = 0, wrong = 0, sum;
String str = "";
Scanner sc;
ArrayList <Integer> mem;
public AddingGame() {
sc = new Scanner(System.in);
rand1 = new Random();
rand2 = new Random();
int r1, r2, i;
mem = new ArrayList <> ();
System.out.println("Input any integer to receive a problem. Answer the problem correctly to proceed. Each correct answer yields a point. After three incorrect attempts, the game ends.");
while (wrong <= 3) {
mem.removeAll(mem);
sum = 0;
i = 0;
str = "";
r1 = rand1.nextInt(5) + 2; // determines the number of terms of a problem
while (mem.size() <= (r1 - 1)) {
r2 = rand2.nextInt(50) + 1; // determines the value of each term
mem.add(r2);
sum += r2;
if (i == (r1 - 1)) {
str = str + mem.get(i) + " = ?";
} else {
str = str + mem.get(i) + " + ";
}
i++;
}
System.out.println(str);
correct();
while (sc.nextInt() != sum) {
System.out.println("Try again!");
System.out.println(str);
wrong++;
if (wrong == 3) {
System.out.println("You're out of attempts!");
break;
}
correct();
}
}
}
private void correct() {
if (sc.nextInt() == sum) {
points++;
if (points != 1) {
System.out.println("Correct! You now have " + points + " points!" );
} else {
System.out.println("Correct! You now have " + points + " point!" );
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire