Skip to content
Advertisement

How do I return to the beginning of a while loop?

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!" );
            }                
        }
    }
}

Advertisement

Answer

I thought you might want to see a simpler implementation of this game, as I noticed you are struggling to figure out what variables you need, what data structures will help etc.!

Hope this helps you understand a bit better how to structure your programs in Java:

import java.util.Random;
import java.util.Scanner;

public class AddingGame {
    Random rand = new Random(); // no reason to have more than one instance of Random
    int points; // ints are automatically initialized to zero
    Scanner sc = new Scanner(System.in);

    public AddingGame() {
        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.");
        mainLoop:
        do { // keep playing until player gives up
            int sum = 0;
            String question = "";
            int termsCount = rand.nextInt(5) + 2; // determines the number of terms of a problem

            for (int i = 0; i < termsCount; i++) {
                int term = rand.nextInt(50) + 1; // determines the value of each term
                sum += term;
                if (i == termsCount - 1) { // this is the last term
                    question += term + " = ? ";
                } else {
                    question += term + " + ";
                }
            }
            System.out.print(question);
            int wrong = 0;
            while (!checkAnswerIsCorrect(sum)) {
                wrong++;
                if (wrong == 3) {
                    System.out.println("You're out of attempts!");
                    break mainLoop; // get out of mainLoop, not just the current one!
                }
                System.out.println("Try again!");
                System.out.print(question);
            }
        } while (shouldContinuePlaying());

        System.out.println("Total Points: " + points);
        System.out.println("GAME OVER!");
    }

    private boolean checkAnswerIsCorrect(int sum) {
        if (sc.nextInt() == sum) {
            points++;
            System.out.println("Correct! You now have " + points + " point" +
                    (points == 1 ? "" : "s") + "!");
            return true;
        }
        return false;
    }

    private boolean shouldContinuePlaying() {
        System.out.print("Continue playing? ");
        return sc.next().equals("yes");
    }

    public static void main(String[] args) {
        new AddingGame();
    }
}

I would recommend splitting up the loops into separate methods after you understand my changes… that will make it much easier for you to “focus” on a single part of the game instead of having to keep everything in your head while you read the code… I moved most fields to local variables because it’s ALWAYS preferrable to have only a small number of things at scope (the variables you can “see”) at any given time – again, to help the programmer understand what values matter and can/should be used.

Good luck and hope you have a great career as a programmer.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement