密码gen和输入不起作用

时间:2016-05-11 19:55:55

标签: java password-generator

我试图创建一个随机密码gen,然后你必须输入必须完全相同的随机密码,但问题是,它总是会说:密码不匹配。因此,即使密码匹配,它仍然无法工作...如果我反转它(所以“如果(!scanner.equals(随机)){”)它说它有效,但那只能反转它,所以这并不奇怪XD这是我的代码:

import java.util.Random;
import java.util.Scanner;

class V20ControlPanel {
public static void main(String[] args) throws InterruptedException {


    Random random = new Random();

    final String alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    final int N = alphabet.length();
    for (int i = 0; i < 4; i++) {
        System.out.print(alphabet.charAt(random.nextInt(N)));

    }

    String s;

    Scanner scanner = new Scanner(System.in);
     s = scanner.nextLine();

    if (random.equals(scanner)) {
        System.out.println("You've succesfully logged in! With password: " +s);
    } else {
        System.out.println("The passwords didn't match, please try again.");


    }
}

}

1 个答案:

答案 0 :(得分:2)

您正在将Random对象与Scanner对象进行比较,而不是您想要获取的值。声明一个局部变量来保存密码:

public static void main(String[] args) throws InterruptedException {

    Random random = new Random();

    final String alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    final int N = alphabet.length();
    String pass = ""; //The variable to hold the password
    for (int i = 0; i < 4; i++) {
        pass += alphabet.charAt(random.nextInt(N)); //Add to password
    }

    String s;

    Scanner scanner = new Scanner(System.in);
     s = scanner.nextLine();

    if (pass.equals(s)) { //Changed
        System.out.println("You've succesfully logged in! With password: " +s);
    } else {
        System.out.println("The passwords didn't match, please try again.");


    }
}

但这仍然是非常低效的代码。您可以考虑更有效地生成随机String的方法。