【问题标题】:I need to ask for a 'Case in-sensitive' code for scanner input. any advice accepted我需要为扫描仪输入请求“不区分大小写”代码。接受的任何建议
【发布时间】:2019-01-07 14:33:06
【问题描述】:

我想知道:有没有办法读取扫描仪输入 '大小写不敏感' whitout 小写还是大写? 我必须做出很多“Y”或“N”的答案,我必须将每个扫描仪输入转换为字符串,然后使用“.toUpperCase”“.toLowerCase”。 我觉得我错过了一些更实用的东西......

我的另一个想法是创建一个扫描器类,将每个输入转换为字符串,然后转换为大写/小写,但我的问题基本上是是否有任何方法可以从一开始就设置它,我可能会错过......

public void acariciar(ArrayList<Animal> animales) {
    System.out.println("Quiere acariciar a estos animales?? Y ó N");

    String inputDeUsuario = escaner.nextLine();
    if (inputDeUsuario.toUpperCase().equals("Y")) {
        for (Animal animal : animales) {
            animal.acariciado();
        }
    }
}

【问题讨论】:

  • 尝试使用 equalsIgnoreCase 而不是 equals。这与扫描仪无关,它由 String 类提供μ

标签: java eclipse java.util.scanner uppercase lowercase


【解决方案1】:

不存在“不区分大小写输入”之类的东西——拉丁字母本身就是大写或小写。但是您可以要求 comparison 忽略被比较字符串的每个字符对之间的大小写差异,String.equalsIgnoreCase():

inputDeUsuario.equalsIgnoreCase("Y")

(如果您处于无法控制相等比较的情况,例如,如果您将字符串添加到 HashSet,那么您的做法是正确的:选择小写或大写,然后转换一切都与那个案子有关。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多