【问题标题】:Checking for 5 punctuation in a list of characters [duplicate]检查字符列表中的 5 个标点符号[重复]
【发布时间】:2013-12-09 04:14:52
【问题描述】:

如何查找用户必须输入的字符列表中是否有“、”“?”“!”“;”“。”,我做了一个while循环,当用户输入任何数字时我打破了它从 0 到 9 ..

示例运行:

Enter any character (a digit 0-9 to stop): a B , R x u ! @ . C W 2
The list you entered contains 3 punctuations signs. 

我所做的一部分

    int count = 1;
    while ( count > 0 )
    { 
        Scanner input = new Scanner(System.in);
        System.out.print("Enter any character and a digit 0-9 to stop: ");
        char ch = input.next().charAt(0);
        if ( ch>=0 && ch<=9)
           break;
    }

原来的q。 :

不断提示用户输入不同于数字的字符的程序。第一个数字 用户输入停止输入,然后程序应显示标点符号的数量 输入的字符(此列表之一!. , ; ?)。找不到时,显示消息“已输入字符 没有标点符号”。

【问题讨论】:

  • 谷歌搜索“正则表达式”。
  • 看上面评论里的链接
  • 你有你尝试过的代码示例吗?
  • 在问题中贴出代码
  • @tomek 我以前读过它,但我认为这不是我要找的……是吗?因为用户输入任何字符,包括双引号。和编。只是告诉他那里有多少双关语..

标签: java string loops while-loop char


【解决方案1】:

Scanner 不是我经常使用且与问题无关的类,因此我将在此处的代码中忽略它,并假设您可以自己完成这些部分。

首先你可以在这里修复你的无限循环:

int count = 1;
while ( count > 0 ) // count is never changed
{
    // ~~

    char ch = /* ~~~~ */;
    if ( ch>=0 && ch<=9) // Unicode codes 0-9 are non-characters
       break;
}

您可以这样做:

while (true)
{
    // ~~

    char ch = /* ~~~~ */;
    if (ch >= '0' && ch <= '9')
       break;
}

while (true) 不是一件坏事,只要你自己的退出条件不模糊并且有效。

为了检查标点符号,您可以设计自己的逻辑。我可以想到三种最简单的解决方案来检查一个字符是否是标点符号:

String punctuationAsString = "!.,;?";

char[] punctuationAsArray = {
    '!', '.', ',', ';', '?'
};

while (true)
{
    // ~~

    char ch = /* ~~~~ */;
    if (ch >= '0' && ch <= '9') {
       break;
    }

    // simple one line
    if (punctuationAsString.contains(ch)) {
        System.out.println("is punctuation");
    } else {
        System.out.println("not punctuation");
    }

    // String#contains basically does this
    boolean punc = false;
    for (int i = 0; i < punctuationAsArray.length; i++) {
        if (ch == punctuationAsArray[i]) {
            punc = true;
            break;
        }
    }

    System.out.println((punc ? "is" : "not") + " punctuation");

    // verbose but clear
    switch (ch) {
        case '!':
        case '.':
        case ',':
        case ';':
        case '?': System.out.println("is punctuation");
                  break;

        default:  System.out.println("not punctuation");
    }
}

【讨论】:

    【解决方案2】:

    试试这个:

        int count = 0;
        String userInput = "a B , R x u ! @ . C W 2";  
    
        if(userInput.matches("^[^\\d].*")){
            Pattern p = Pattern.compile("[!,./;?]");
            Matcher m = p.matcher(userInput);
            while (m.find()){
                count++;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 2014-03-07
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      相关资源
      最近更新 更多