为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

隔江千里 2021-10-27 16:30:47
在这个程序中,我希望 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}}
查看完整描述

1 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

每次调用getGuess时都会返回不同的值。里面的代码checkPassword()有问题。就是在这里,


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

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

} else {

    getDigitsOf(getPassword(), getGuess());

}

请注意,您有两次调用getGuess. 而是将值保存在本地。喜欢,


int guess = getGuess(), pass = getPassword();

if (guess == pass) {

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

} else {

    getDigitsOf(pass, guess);

}


查看完整回答
反对 回复 2021-10-27
  • 1 回答
  • 0 关注
  • 107 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信