jrmullen
jrmullen

Reputation: 346

Incrementing a variable within a loop in Java

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.

Upvotes: 0

Views: 92

Answers (1)

shmosel
shmosel

Reputation: 50716

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

Upvotes: 4

Related Questions