如何使字符串比较不区分大小写? [英] How to make a string compare non case sensitive?
问题描述
我正在尝试根据您的答案为其中一个程序编写代码。我想这样做,以便一些变量不区分大小写。例如,如果我的变量 x
等于我
我希望它也等于 我
。这可能吗?
I am trying to write a code for one of those programs that responds according to your answers. I want to make it so that some of the variables are not case sensitive. For example if my variable x
is equal to "Me"
I want it to also equal "me"
. Is that possible?
这是我到目前为止的代码:
Here is my code so far:
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner N = new Scanner(System.in);
String name = N.next();
if (name.equals("me") || name.equals("Me")){
System.out.println("Well, good for you smartass.");
System.exit(1);
}else System.out.printf("Nice to meet you, %s.%n", name);
System.out.print("How are you doing?");
Scanner d1 = new Scanner(System.in);
String doing = d1.next();
switch(doing){
case "good": System.out.println("that is nice to hear.");
case "Well": System.out.println("that is nice to hear.");
case "bad" : System.out.println("That's ruff mate.");
case "Awesome" : System.out.println("Nice");
case "Terrible" : System.out.println("Sucks for you");
}
}
}
我不喜欢我不想为每个答案制作2个案例,其中一个是大写,另一个是小写。
I don't want to have to make 2 cases for each answer where one is uppercase and the other is lower case.
稍微偏离主题问题。如何关闭扫描仪的资源泄漏?
Slightly off topic question. How do I close the resource leaks for the scanner?
推荐答案
值得一提 字符串#toLowerCase
:
name.toLowerCase().equals("me");
或者只需使用 String #equalsIgnoreCase
:
Or simply use String#equalsIgnoreCase
:
name.equalsIgnoreCase("me");
这篇关于如何使字符串比较不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!