I want to know the number of letters in the word and know if it is odd or the even | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I want to know the number of letters in the word and know if it is odd or the even

public static void main(String[] args) { String res ="welcom to the new world you may love it or hate it but you have to adapt to it anyway" + "you will remain in this world for afew monthes or years so you have to work and take adavantage" + "of it so as not to waste this time and get used to the idea of balance between the surrounding" + " environment and professional life. "; String [] str=res.split(" "); int r =res.length(); for(String s :str) if(r%2==0){ System.out.println(s+"even"); } else System.out.println(s+" "+"odd"); } }

13th Jun 2022, 8:42 PM
Fatma hgazy
Fatma hgazy - avatar
2 Answers
+ 3
String[] str = res.split(" "); this will make your array of words, I would recommend you to rename your variables to be more representative, it will help a lot. then you do int r = res.length(); this here is your mistake, you are getting the lenght of the whole text in your variable r instead get the lenght of the individual words String[] words = text.split(" "); for(String word : words) { int characters = word.length(); ... } I hope this helps :)
13th Jun 2022, 9:21 PM
Apollo-Roboto
Apollo-Roboto - avatar
+ 3
// Hope this code helps you.¯\_(ツ)_/¯ https://code.sololearn.com/c5ton7F7QLKF String[] str = Sentence.split(" "); int len, evenCnt=0, oddCnt=0; String res; for(String s : str) { len = s.length(); if(len%2 == 0) { evenCnt++; res = s + "\t [" + len + "] even"; } else { oddCnt++; res = s + "\t [" + len + "] odd"; } System.out.println(res); } System.out.format("\nEven Words Count: %d \nOdd Words Count: %d", evenCnt, oddCnt);
13th Jun 2022, 11:43 PM
SoloProg
SoloProg - avatar