简体   繁体   中英

how to reduce number of tries left in java

        if(guess.equals(selection)){
            System.out.println("win");
            System.exit(0);
        }else if(attemptsLeft <= 0){
            System.out.println("loose");
        }else  {
           attemptsLeft--;
           System.out.println("retry, tries left  " +" " + attemptsLeft);

        }

I want it for every wrong guess to decrease number of tries by 1. This code decreases it from 3 to 2 but not from 2 to 1. No matter how many mistakes its always gonna print "retry, tries left 2"

You have to declare the variable outside of the method block, cause the block will init a new variable (as 3) at every method call:

Declare it as a class field:

    int attempsLeft = 3;
    private void evaluateGuess() {
        //rest

This way the value will be kept between method calls inside the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM