【问题标题】:Java, Eclipse. How to allow a scanner to read both lower and uppercase?爪哇,日食。如何让扫描仪同时读取小写和大写?
【发布时间】:2014-03-13 07:09:35
【问题描述】:

首先我想说你们很棒。我从你们大家身上学到了很多。我的问题是如何让我的扫描仪读取用户的大写和小写输入?我的代码如下。

Scanner anotherScanner = new Scanner(System.in);
boolean usersSelection = false;
String c;
while (!usersSelection) {
    System.out.println("Selection: ");
    if (anotherScanner.hasNext("q")) {
        c = anotherScanner.next();
        usersSelection = true;
        System.out.println("you have selected to quit");
    }
    if (anotherScanner.hasNext("t")) {
        c = anotherScanner.next();
        usersSelection = true;
        System.out.println("you have selected the coin toss estimator");
    }
    if (anotherScanner.hasNext("g")) {
        c = anotherScanner.next();
        usersSelection = true;
        System.out.println("you have selected the grade estimator");
    }
    if (anotherScanner.hasNext("c")) {
        c = anotherScanner.next();
        usersSelection = true;
        System.out.print("You have selected color Challenge");
    } else {
        String zoom = anotherScanner.next();
        System.out.println("You have entered an invalid option. '"
            + zoom + "' is not a valid option.");
    }
}

我想根据用户的选择(不区分大小写)进行操作,即用户输入“Q”还是“q”。

【问题讨论】:

  • 你是说你的扫描仪不区分大小写吗?它应该自动这样做
  • 我认为他们是在说他们希望 hasNext("x") 不区分大小写。
  • Scanner 支持正则表达式,所以像anotherScanner.hasNext("q|Q") 这样的东西可能会起作用
  • 可行吗?可能有用吗? @MadProgrammer,您的意思是“会起作用”。当然,假设这就是 OP 的实际要求。这是有待商榷的部分。
  • 当我运行程序时,如果我输入,它会提示我选择 (g,c,t,q),例如 c 它会显示“您已选择颜色挑战”。但是,如果我输入 C(大写),它会显示“您输入了一个无效选项。我的问题是如何让扫描仪忽略大小写或将用户输入转换为像大写一样读取它?

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


【解决方案1】:

扫描仪支持正则表达式,因此您可以使用 anotherScanner.hasNext("q|Q") 之类的东西来代替

【讨论】:

    【解决方案2】:

    改成这个,

    1)。

    anotherScanner.hasNext("q") || anotherScanner.hasNext("Q")
    

    2)。

    anotherScanner.hasNExt("q|Q");
    

    实现任何人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 2016-01-16
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多