[英]Java code not running as planned
这不是整个代码,只是问题所在。 (下面的完整代码)
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
我正在制作一个程序,用户在该程序中创建一个帐户,然后登录。我遇到的问题是验证,以确保用户是人(显然是,但仍然)。 创建他们的用户名和密码后,我生成并打印一个随机int,他们必须将其键入回来。
我的问题是程序总是跳到else
语句,并显示"The code entered is incorrect."
即使我输入完美。
谁能告诉我我在做什么错?
下面是完整的代码,以防万一。
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out
.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
您正在将String与整数进行比较,这显然不能相同。
int randm = rand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm))
要解决该问题,您可以将整数转换为String并比较字符串(或以其他方式)。
String randm = String.valueOfrand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm)) // Comparing string now
编辑:正如@Pshemo指出的那样, int code = userInput.nextInt();
假设您将整数与==
进行比较,它将完成工作。
这是因为randm是int而代码是String。 因此,代码if (code.equals(randm))
总是结果为false。
您不能比较字符串和整数。 尝试将输入作为整数而不是字符串。 String code = userInput.next();
而是使用:
int code= userInput.nextInt();
if(code==randm)
或者您也可以将整数转换为字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.