无论输入如何,它始终给出第二个条件。 (userName ==“ Charles”)是否是有条件的正确方法?还是我需要其他东西?
import java.util.Scanner;
public class Name_input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName = input.next();
System.out.println(userName);
if (userName == "Charles")
{
System.out.println("Correct Name");
}
else if (userName != "Charles")
{
System.out.println("Incorrect Name");
}
}
}
答案 0 :(得分:-2)
(userName ==“ Charles”)是执行此条件的正确方法
否您不使用“ ==”来比较字符串。
相反,您应该使用equals(...)
方法:
if ( "Charles".equals( userName ) )
请注意,我颠倒了比较的顺序。如果用户名为空,这将阻止NPE。
System.out.println(userName);
是否显示期望值?您需要使用trim()方法吗?
else if (userName != "Charles")
此外,也不需要“ else if”。名称要么是“ Charles”,要么不是,所以您不需要其他的“ if”语句。