[我注意到扫描仪中的next()
方法“从该扫描仪中查找并返回下一个完整令牌。”然后我使用它,如下所示:
public static void main(String[] args) {
System.out.println(menu);
Scanner scanner = new Scanner(System.in);
String command = scanner.next();
System.out.printf("command is \"%s\".", command);
System.out.println(command == "5");
while (command != "5") {
switch (command) {
case "1": // update the database
System.out.println("Enter first name: ");
String firstName = scanner.next();
System.out.println("Enter last name: ");
String lastName = scanner.next();
System.out.println("Enter email address: ");
String emailAddress = scanner.next();
System.out.println("Is paying member (T or F): ");
String isPayingMember = scanner.next();
System.out.println("Is staff member (T or F): ");
String isStaff = scanner.next();
System.out.println("Is problem contributor (T or F): ");
String isProblemContributor = scanner.next();
System.out.println("Enter subscription start date (as MMDDYY, e.g., 120219):");
String startDate = scanner.next();
if (isFormatCorrect(firstName, lastName, emailAddress, isPayingMember, isStaff,
isProblemContributor, startDate)) {
update();
}
break;
default:
System.out.println(warning);
System.out.println(menu);
command = scanner.next();
break;
}
}
scanner.close();
System.out.println("Exiting...");
System.out.println("Done");
并且我得到了如下所示的输出:
1) Enter member information
2) List the member(s) who have paid more than $400
3) Add a problem into a specified problem pool
4) List the problems and problem pools that each member has
5) Quit
Enter 1-4 or 5 to quit:
5
command is "5".false
Warning: Invalid input, please try again!
1) Enter member information
2) List the member(s) who have paid more than $400
3) Add a problem into a specified problem pool
4) List the problems and problem pools that each member has
5) Quit
Enter 1-4 or 5 to quit:
它说字符串command
不等于“ 5”,这真让我感到困惑。但是,在使用nextInt()
的Scanner
方法后,它可以正常工作。是什么原因呢?
我正在MacOS 10.15.1和Java(TM)SE Runtime Environment(内部版本1.8.0_221-b11)下工作
如果要比较Java中的字符串,则必须使用equals方法。
while (command.equals("5")) {
...
}
您的输入是字符串,而不是整数。然后,您不能使用==运算符比较2个字符串,必须使用equals方法。
[command.equals("5")
而不是command == "5"
有关Java中字符串比较的更多信息,请参见this post。>>
基本上,==运算符比较2个字符串的引用,等于比较值。您要比较这些值。