我想知道如何在我的方法中使用任何用户输入来忽略大小写:
public static void findPatient() {
if (myPatientList.getNumPatients() == 0) {
System.out.println("No patient information is stored.");
}
else {
System.out.print("Enter part of the patient name: ");
String name = sc.next();
sc.nextLine();
System.out.print(myPatientList.showPatients(name));
}
}
你必须在输入和你想要匹配的字符串上使用String方法.toLowerCase()
或.toUpperCase()
。
例:
public static void findPatient() {
System.out.print("Enter part of the patient name: ");
String name = sc.nextLine();
System.out.print(myPatientList.showPatients(name));
}
//the other class
ArrayList<String> patientList;
public void showPatients(String name) {
boolean match = false;
for(matchingname : patientList) {
if (matchingname.toLowerCase.contains(name.toLowerCase())) {
match = true;
}
}
}
使用String#toLowerCase()
或String#equalsIgnoreCase()
方法
一些例子:
String abc = "Abc".toLowerCase();
boolean isAbc = "Abc".equalsIgnoreCase("ABC");
.equalsIgnoreCase()方法应该有帮助。
使用String类的toUpperCase()或toLowerCase()方法。
您在处理数据时忽略大小写,而不是在检索/存储数据时忽略大小写。如果你想以小写形式存储所有内容,请使用String#toLowerCase,大写使用String#toUpperCase。
然后,当你必须真正对待它时,你可以使用弓箭方法,如String#equalsIgnoreCase(java.lang.String)。如果Java API中不存在满足您需求的任何内容,那么您将必须编写自己的逻辑。
我也尝试了所有发布的代码,直到我发现了这个
if(math.toLowerCase(Locale.ENGLISH));
这里用户输入的任何字符都将转换为小写字母。