【问题标题】:Input sentence and print out number of words that are above min length requirement in java在java中输入句子并打印出超过最小长度要求的单词数
【发布时间】:2013-11-08 20:56:38
【问题描述】:

我的目标是创建一个接受字符串的代码,以及每个单词允许的最小字符数。输出将是一个 int 值,告诉用户他们句子中大于或等于他们输入的最小值的单词数。

现在,我的方法是在 main 方法中将句子分解为单个单词,然后将每个单词发送到另一个计算字符数的方法中。

我的主要方法有困难,特别是将句子分成单个单词。我想在不使用数组的情况下实现这一点,只使用循环、子字符串和 indexOf 等。我评论了我遇到问题的代码部分。我使用只有一个单词的字符串测试了我的其余代码,并且我的 letterCounter 方法似乎工作正常。我知道答案可能很简单,但我仍然无法弄清楚。

任何帮助都会很棒!谢谢!

这是我的代码:

public class Counter
{
public static void main(String [] args)
{
    int finalcount = 0;

    System.out.print("Enter your string: ");
    String userSentence = IO.readString();


    System.out.print("Enter the minimum word length: ");
    int min = IO.readInt();

    //Error checking for a min less than 1

    while(min < 0)
    {
        IO.reportBadInput();
        System.out.print("Enter the minimum word length: ");
        min = IO.readInt();
    }


    int length = userSentence.length(); // this will get the length of the string



    for(int i = 0; i < length; i ++)
    {
         if (userSentence.charAt(i) == ' ')
         {  

             /* I dont know what to put here to split the words!

                  once I split the userSentence and store the split word into
                  a variable called word, i would continue with this code: */

            if((letterCounter(word)) >= min)
                finalcount++;

            else
                finalcount = finalcount;

           }
    }       




    IO.outputIntAnswer(finalcount);

}

//this method counts the number of letters in each word

    public static int letterCounter (String n)
        int length = n.length(); 
        int lettercount= 0;


     for(int i = 0; i < length; i ++)

    {
        boolean isLetter = Character.isLetter(n.charAt(i));

         if (isLetter) 
         {
            if ((n.length()) >= length) 
            {
                lettercount++;
            }
         }

    }

    return lettercount;
 }

}

【问题讨论】:

  • 您的问题标题具有误导性。似乎您想计算句子中的单词数(并应用一些限制规则),但在描述中您说限制与句子中每个单词的长度有关。好像大家都懒得看问题,只看标题,所以请修正一下。

标签: java string


【解决方案1】:

您可以像这样使用 string.split() 来完成此操作:

String [] splittedString  = inputString.split(" ");

for(int i = 0;i< splittedString.length; i++){
    String currentWord = splittedString[i];

    if(currentWord.length() >= min){
        finalcount++;
    }
}

【讨论】:

    【解决方案2】:

    【讨论】:

    • 虽然 split 返回一个数组,这显然是不需要的。虽然我有疑问。
    • 糟糕,错过了那部分
    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2012-10-27
    • 2021-04-05
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多