java - 输入句子并打印出java中超过最小长度要求的单词数

标签 java string

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

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

我的主要方法遇到了困难,特别是将句子分成单独的单词。我想在不使用数组、仅循环、子字符串和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 - 输入句子并打印出java中超过最小长度要求的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662704/

相关文章:

java - 是否有更好的方法来分析作为示例给出的输入/输出数组之间的路径?

java - 未记录的 String.compareTo(null) NPE?

c# - IoC/DI 容器、工厂和运行时类型创建

javascript - 如何在angularJS中将字符串转换为数组

Python 3 : using %s and . 格式()

python - 将正则表达式结果保存到变量中

java - Wicket 6 NonCachingImage 未在 HTML 中显示

java - Mockito:使用回调方法模拟两个返回值

c - 如何将字符串可移植地转换为不常见的整数类型?

linux - 如何将日期字符串添加到连续写入的日志文件的每一行