我的代码有问题。这是过程 -
可以毫无问题地输入名称和年龄,但程序会错误地评估密码。当您正确输入密码时,它仍会返回false。
请帮帮我!! 感谢。
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
String name;
int age;
boolean trueOrFalse;
boolean trueOrFalse2;
String builtInPassword = "anybody";
Scanner keyBoardInput = new Scanner(System.in);
System.out.print("Please enter your First name: ");
name = keyBoardInput.next();
System.out.print("Please enter your age: ");
age = keyBoardInput.nextInt();
trueOrFalse = false;
trueOrFalse2 = true;
System.out.print("Please enter your Password: ");
if (keyBoardInput.next() == builtInPassword) {
System.out.println(trueOrFalse2);
} else {
System.out.println(trueOrFalse);
}
}
}
答案 0 :(得分:3)
在比较Java中的两个字符串时,您希望使用.equals()方法。这将比较两个字符串的值,而==将比较参考。
String test = "test";
if(test.equals("test")) {
//Do something
}
答案 1 :(得分:0)
你需要在字符串上使用.equals(),如下所示:
public static void main(String[] args) {
String name;
int age;
boolean trueOrFalse;
boolean trueOrFalse2;
String builtInPassword = "anybody";
Scanner keyBoardInput = new Scanner(System.in);
System.out.print("Please enter your First name: ");
name = keyBoardInput.next();
System.out.print("Please enter your age: ");
age = keyBoardInput.nextInt();
trueOrFalse = false;
trueOrFalse2 = true;
System.out.print("Please enter your Password: ");
if (keyBoardInput.next().equals(builtInPassword)) {
System.out.println(trueOrFalse2);
} else {
System.out.println(trueOrFalse);
}
}
答案 2 :(得分:0)
谢谢你解决了我的问题。 我发现了另一种方式:
if (keyBoardInput.hasnext(builtInPassword)) {
System.out.println(trueOrFalse2);
} else {
System.out.println(trueOrfalse)
}