简体   繁体   English

Java - 字数统计真假

[英]Java - Word Count True or False

i have a programming task using java...我有一个使用 java 的编程任务...

public class CountWords{  
public static void main(String[] args) {  
    String sentence = "Papa beauty lies in the eyes of beholder";  
    int wordcount = 0;  
      
    for(int i = 0; i < sentence.length()-1; i++) {  
        if(sentence.charAt(i) == ' ' && Character.isLetter(sentence.charAt(i+1)) && (i > 0)) {  
            wordcount++;  
        }  
    }  
    wordcount++;
    
    System.out.println("Total number of words: " + wordcount);  
    System.out.println(sentence.startsWith("P"));
}}  

My question is how can i define the String sentence based on this condition:我的问题是如何根据此条件定义 String 句子:

  1. If more than 3 words, it will be True.如果超过 3 个单词,则为 True。
  2. If less than 4 words, it becomes False.如果少于 4 个单词,则变为 False。

Thankyou so much for helping..非常感谢你的帮助..

If I understand your question correctly...如果我正确理解你的问题......


 /* returns string array of tokens (words in the sentence) after splitting by space */
String[] tokens = sentence.split(" ");

if(tokens.length() > 3) {
  // true
} else {
  // fasle
}

Let's have a look at the steps we should take in order to achieve your goal in a easier way;让我们来看看我们应该采取的步骤,以便更轻松地实现您的目标;

  1. First, let's count the number of words in your input string via count function首先,让我们通过 count function 计算输入字符串中的单词数

  2. Call the function by sending our input sentence通过发送我们的输入语句来呼叫 function

  3. Function returns number of words Check the number of words for any condition you desire Function 返回字数 检查您想要的任何条件的字数

Therefore your code will work better like this;因此你的代码会像这样更好地工作;

public class CountWords{  

public static void main(String[] args) {  

    String sentence = "Papa beauty lies in the eyes of beholder";
    private bool coniditon;
    int wordcount = count(sentencte);
      

    if (wordcount<4) {
        condition=False;
        }
    else if (wordcount>3) {
        condition=True;
        }

    System.out.println("Total number of words: " + wordcount);  
    System.out.println(sentence.startsWith("P"));

     
  }


public static int count(String sentence){ 

     if(sentence == null || sentence.isEmpty()){ 
        return 0; } 

      String[] words = sentence.split("\\s+");
      return words.length; }
   }

}

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM