我试图创建一个随机密码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.");
}
}
}
答案 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
的方法。