0 java string compare equality equals
我正在为课程编写一个程序,我在其中分析输入的不同产品代码.这很简单,但我遇到了问题.如果用户输入"E"或"e",我试图结束循环.但是,它根本不会结束循环.这是在while语句的末尾,所以将循环设置为false应该结束它,它甚至不输出总数,所以我搞砸了一些东西.代码是字符串类型.
// Prompt the user for another company code or exit
System.out.print("Enter the company code or type 'e' to exit: ");
// Input the user's company code
code = scan.nextLine();
// Check to see if the user wants to exit
if (code == "e" || code == "E") {
// Output final statistics
System.out.print("Total valid codes: " + valid + "/n");
System.out.print("Total banned codes: " + banned);
// End the loop
loop = false;
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢!
你需要使用code.equals("e") || code.equals("E")(或只是code.equalsIgnoreCase("e")).这是因为==不认同比较("是X和Ÿ相同的对象?"),而equals做价值比较("做X和Ÿ具有相同的价值?").