how to count the number of words in a sentence in java using array? -
Then here's the Mw code I have tried. It's incomplete .. Please correct me
< Pre> Import java.util.Scanner; Public class Q5 {public static zero main (string [] args) {scanner input = new scanner (System.in); Four sizes; Four [] sentences; Int vocabulary = 0, wordconverter = 0; System.out.print ("Please enter a line of text:"); Sentence (i = 0; i & lt; size; i ++) {if (sentence [i] == 'a' || sentence [i] == 'e' || sentence [i] == 'o' || Sentence [ii] == 'I' || Sentence [I] == 'U'); {Note-mark ++; } If (sentence [i] == 32) {wordcounter ++; }} System.out.print ("Number of words:" + Word counters); System.out.print ("The number of voices:" + vowelcounter); }}
You use String.split () can do . It divides the string objects into string in string in string on a delimiter basis.
string [] sentence = sentence. Split (""); Then just check the size of the array
int wordCount = wordwords.length; It should also be noted that your code is not wrong for counting vowels. You should check each letter of each word and see if it is a vowel instead of comparing the word.
Then repeat each character of each word
(int i = 0; i s.length (); i ++) {char ch = s.charAt (i); } Then check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch = = 'I' || f == 'o' || cc == 'u') {voice count ++; } The full example is:
public static BufferedReader br = new BufferedReader (New InputStreamReader (System.in)); Public static zero major (string [] args) exception {string input = br.readLine (); String [] word = input.split (""); System.out.println ("sets in settings:" + words.length); Int vow number = 0; (For string: word) {for (int i = 0; i & lt; s.length (); i ++) {char ch = s.charAt (i); If (f == 'a' || f == 'e' || f == 'i' || cc == 'o' || c == 'u') {note count ++; }}} System.out.println (number of vowels in sentence: "+ vowelCount"); } and when I input:
test this program I get the output:
Word in Sentence: Number of Voices in Sentence: 5
Comments
Post a Comment