0

I'm working on a dice game in which I want to allow the user to keep some of their rolls, and then reroll others. I store their first 5 rolls in an array called dieArray and then print the contents of this array, each die being numbered, and then ask the user which die he/she wants to keep, looping one at a time.

The idea was to then add the value of the die that the user chose to keep to a new array that I called keepArray.

My current code for this loop is as follows

while(bool != false){
        System.out.print("Would you like to keep a die? y/n: ");
        char ch = scanner.next().charAt(0);


        if(ch == 'n') {
            System.out.println("Exiting----------------------------------------------");
            bool = false;
        }
        else{
            System.out.print("Which die number would you like to keep?: ");
            int keep = scanner.nextInt();
            int i = 0;
            keepArray[i] = die.dieArray[keep];
            i++;
            System.out.println("i value is " + i);
        }
    }

The issue I am having is that my i within the else statement is not being incremented. I feel that I am not understanding the fundamentals of while loops in Java, because as I see it each time the else loop is accessed, which should be every time the user answers "y" when asked if he/she wants to keep a die, my i should be incremented by 1. Clearly it is not.

1
  • 1
    As a side note, any comparison using ==, <, >, <=, >=, or != will return a boolean. For example writing 1 != 2 is the same as writing true. With this in mind, if your variable bool is false, then bool != false will return false; if bool is true, then bool != false will return true. So you can just write while(bool) instead of while(bool != false). Commented May 18, 2016 at 0:59

1 Answer 1

4

Your i variable is being recreated on every round. You need to declare int i = 0; above the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.