i have a programming task using 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:
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;
First, let's count the number of words in your input string via count function
Call the function by sending our input sentence
Function returns number of words Check the number of words for any condition you desire
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.