在此程序中,我希望getGuess打印一条错误消息,然后在满足条件的情况下(如果猜测值落在特定范围内)则进行粗调,如果不满足,则返回猜测值。

但是,当我运行此命令时,某些数字导致再次调用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
}


}

最佳答案

每次调用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);
}

10-01 07:45