我是JAVA编程的新手,现在我面临一个奇怪的案例。我将确认变量设置为String类型,它将保存用户输入。当用户输入“是”时,程序应该创建一个新用户,但事实并非如此。相反,它会引发误报“用户取消进程”。似乎没有正确评估转发变量。任何建议的人。感谢。
这是我的代码(虽然很简单):
import java.util.Scanner;
public class CreateUser {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String firstName;
String lastName;
String confirmation;
System.out.println("Create new user");
System.out.print("Enter first name : ");
firstName = input.nextLine();
System.out.print("Enter last name : ");
lastName = input.nextLine();
System.out.println("Are you sure?");
confirmation = input.nextLine();
System.out.println(confirmation); // this line is to make sure that the variable value is "yes"
if(confirmation == "yes")
{
Users newUser = new Users(firstName, lastName);
System.out.printf("User %s %s has been created\n", firstName, lastName);
System.out.println("Total active users now is :"+Users.getRegisteredUsers());
}
else
{
System.out.println("Process is canceled by user");
}
input.close();
}
}
这是输出:
Create new user
Enter first name : fin
Enter last name : fin
Are you sure?
yes
yes
Process is canceled by user
答案 0 :(得分:2)
使用
if (confirmation.equals("yes")) {
}
而不是
if(confirmation == "yes")
.equals()
比较2个字符串的值。 ==
比较内存引用以查看它们是否指向同一个对象。
Reference article