猿问

为什么我的方法在递归的唯一条件尚未满足时递归?

在这个程序中,我希望 getGuess 打印一条错误消息,然后在满足条件时进行 rucurse(如果猜测在特定范围内),如果不满足,则返回 guess 的值。


但是,当我运行它时,某些数字会导致再次调用 getGuess,但没有错误消息。为什么会这样?


import java.util.Scanner;


public class Password {

public static int difficulty = 4;


public static void main(String[] args) {

    System.out.println("Password Cracker by Noah White Beta (v 1.0.0)");

    checkPassword();

    // getDigitsOf(1235, 17356);

}


public static int getRange() {

    int range = (int) Math.pow(10, difficulty);

    return range;

}


public static int getPassword() {


    double randomRaw = Math.random();

    int random = (int) (randomRaw * getRange() + 1);

    // System.out.println(random);

    return random;

}


public static int getGuess() {


    Scanner in = new Scanner(System.in);

    System.out.println("ENTER PASSWORD_");

    int guess = in.nextInt();


    // boolean error = 1547 > (getRange() - 1) || 1547 < (getRange() / 10 );


    if (guess > (getRange() - 1) || guess < (getRange() / 10)) {

        System.out.println("ERROR: INVALID_PASSWORD");

        return getGuess();


    } else {

        System.out.println("stop");

        return guess;

    }


}


public static void checkPassword() {


    if (getGuess() == getPassword()) {

        System.out.println("PASSWORD_ACCEPTED LOGGING_IN...");

    } else {

        getDigitsOf(getPassword(), getGuess());

    }

}


public static void getDigitsOf(int password, int guess) {


    // breaks guess number into 4 seperate digits

    int fourthDigit = guess % 10;

    int thirdDigit = (guess / 10) % 10;

    int secondDigit = (guess / 100) % 10;

    int firstDigit = guess / 1000;


    int passFourthDigit = password % 10;

    int passThirdDigit = (password / 10) % 10;

    int passSecondDigit = (password / 100) % 10;

    int passFirstDigit = password / 1000;


    // test

    System.out.println(firstDigit);

    System.out.println(secondDigit);

    System.out.println(thirdDigit);

    System.out.println(fourthDigit);


    // add if/else's for multiple difficulty

}

}


隔江千里
浏览 110回答 1
1回答

ibeautiful

每次调用getGuess时都会返回不同的值。里面的代码checkPassword()有问题。就是在这里,if (getGuess() == getPassword()) {&nbsp; &nbsp; System.out.println("PASSWORD_ACCEPTED LOGGING_IN...");} else {&nbsp; &nbsp; getDigitsOf(getPassword(), getGuess());}请注意,您有两次调用getGuess. 而是将值保存在本地。喜欢,int guess = getGuess(), pass = getPassword();if (guess == pass) {&nbsp; &nbsp; System.out.println("PASSWORD_ACCEPTED LOGGING_IN...");} else {&nbsp; &nbsp; getDigitsOf(pass, guess);}
随时随地看视频慕课网APP

相关分类

Java
我要回答