我正在尝试为其中一个根据您的回答做出响应的程序编写代码。我想让一些变量不区分大小写。例如,如果我的变量 x
等于 "Me"
,我希望它也等于 "me"
。这可能吗?
到目前为止,这是我的代码:
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");
}
}
}
我不想为每个答案都分两种情况,一种是大写,另一种是小写。
稍微偏离主题的问题。如何关闭扫描器的资源泄漏?
最佳答案
值得一提String#toLowerCase
:
name.toLowerCase().equals("me");
或者简单地使用 String#equalsIgnoreCase
:
name.equalsIgnoreCase("me");
关于java - 如何使字符串比较不区分大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22293801/