【问题标题】:How to check to make sure user entry matches a certain beginning character [duplicate]如何检查以确保用户输入与某个开始字符匹配[重复]
【发布时间】:2020-11-14 22:07:40
【问题描述】:

我正在编写一个程序,它使用扫描仪获取用户输入并检查它是否以 y 或 Y 开头来执行操作。任何其他条目都将被视为错误并执行不同的操作。

Scanner scnr = new Scanner(System.in);
String userInput;
userInput = scnr.next().charAt(0);
if (userInput.equalsIgnoreCase("y"))

这是我此时的想法,但这不是我的完整代码。我知道 string 和 char 不兼容,但我不确定还能如何做到这一点。我也不只是想像这样在 if 语句中放置条目的多个变体

if (userInput.equalsIgnoreCase("y") || userInput.equalsIgnoreCase("yup"))

我希望这个问题有意义。我是编程和这个网站的新手,所以如果这很明显,我很抱歉!

【问题讨论】:

  • 有没有理由不把字符当成char来比较呢?如果您只关心输入的第一个字符是“y”或“Y”,myChar == 'y' || myChar == 'Y' 就可以正常工作。
  • @ChrisGong 谢谢!我一直在寻找这个问题的答案很长时间,但由于某种原因我完全错过了那个帖子。我最终使用了 .substring(0,1).equalsIgnoreCase("Y") 并且它现在可以工作了!

标签: java


【解决方案1】:

像这样尝试:

userInput = scnr.next();
if (userInput.toLowerCase().startsWith("y")) {
   //if input start with y or yup : do something
}
else{
  //else : do another thing         
}

【讨论】:

  • 这也可以接受吗? (userInput.substring(0,1).equalsIgnoreCase("Y"))
  • @dlawil2049 这也有效,因为 substring(begin,end) 返回 begin 之间的字符串结束-1
  • 你也需要检查一个String是否为空。因为如果是那么它会给你一个错误
  • @SwapnilPadaya scnr.next() 不能返回空字符串,但是如果他使用 scnr.nextLine() 这会导致 StringIndexOutOfBoundsException
【解决方案2】:

您也可以使用正则表达式作为输入:

    String str = "Your String";
    Pattern pattern = Pattern.compile("y.*|Y.*");
    Matcher matcher = pattern.matcher(str);
    if (matcher.matches()) {
        System.out.println(str); // Display the string.
    }

【讨论】:

    猜你喜欢
    • 2021-08-24
    • 2019-04-03
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多