gpt4 book ai didi

Java 代码未按计划运行

转载 作者:行者123 更新时间:2023-11-29 03:06:36 25 4
gpt4 key购买 nike

这不是完整的代码,只是问题区域。 (完整代码如下)

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");

}

}

最佳答案

你正在比较一个字符串和一个整数,这显然是不一样的。

int randm = rand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm))

要解决此问题,您可以将整数转换为字符串并比较字符串(或其他方式)。

String randm = String.valueOfrand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm)) // Comparing string now

编辑:正如@Pshemo 指出的那样,int code = userInput.nextInt();将完成工作,因为您将整数与 == 进行比较.

关于Java 代码未按计划运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31888232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com