Count Words in a String and Output First Four
Greetings JF!
I am new to Java and to programming in general. I am working on a program that will input a string and count the number of words in it. Then, if there are less than four words, it will output the four words. If there are four or more words, it will output the first four, and inform the user how many words were truncated.
I've completed the word count section:
import java.util.Scanner;
public class WordCount
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
String lineOfText;
System.out.println("Please enter a line of text:");
lineOfText = kb.nextLine();
int i = 0, numberOfWords = 0;
while (i < lineOfText.length())
{
if(lineOfText.charAt(i) == ' ')
{
numberOfWords++;
}
i++;
}
numberOfWords = numberOfWords + 1;
//System.out.println("The number of words is: " + numberOfWords);
At this point I think I need to have an if condition:
if (numberOfWords<4)
System.out.println("The words you have entered are: " + lineOfText);
But this is inelegant: I am just repeating the entire string, not the words only. My guess is that I can use some kind of indexing method in order to break the string into substrings, and then to print those substrings. I am not quite sure how to do this. I have tried several times to no avail. I suppose I could also break the string up into arrays, but I'm not sure how to do that either.
Would anyone mind helping me out with this one?
Re: Count Words in a String and Output First Four
Code:
String[] words = lineOfText.split(" ");
numberOfWords = words.length(); // or words.size(), cannot remember.
Re: Count Words in a String and Output First Four
Could you explain what that code will do?
Re: Count Words in a String and Output First Four
lilezek seems to be making up things. His posted code has errors in it.
The split() method will parse/split the String it is called on according to the regular expression passed to it as an argument.
If there is only a single space between words, the example given above would work. If there can be more than one space between words then there needs to be a better reg exp.
To see what the results of split are, use the Arrays toString() method to format the array for printing:
Code:
System.out.println("words="+Arrays.toString(words));
Re: Count Words in a String and Output First Four
Quote:
Originally Posted by
RSH
Could you explain what that code will do?
Sorry, I thought the name of the method "split" would be self-explainatory.
That method splits into an array of Strings every token between each ocurrence of the REGEX expression.
I sadly admit I don't know so much about REGEX, but all your words are separated by one space this would do the work.
Re: Count Words in a String and Output First Four
I tested it. @Norm is right, you need PRX to judge the number of words .Fortunately I am a little good at it .
But Due to criticism from Jos and others , I only post a segment of my code.
Code:
System.out.println("Please enter a line of text:");
String[] lineOfText = kb.nextLine().split("\\W+");
int numberOfWord = lineOfText.length ;
if ( numberOfWord <= 4 ) System.out.println(lineOfText) ;
else {
System.out.println("The first four words is: " +
lineOfText[0]+" "+lineOfText[1]+" "+lineOfText[2]+" "+lineOfText[3]);
System.out.println("The number of words is: " + numberOfWord); }
Ksharp
Re: Count Words in a String and Output First Four
Thanks for all your help, guys. I still haven't entirely got the hang of arrays. Ksharp - when I tried your code it compiled fine, however, if the user enters four or less words, instead of printing the words, "[Ljava.lang.String;@1e4cbc4" is printed out. Do I need to convert the array to a string of some sort?
Re: Count Words in a String and Output First Four
See the Arrays class's toString() method as a way to format the contents of an array for printing.
Re: Count Words in a String and Output First Four
Yes.
That is the memory address of the String[].
Ksharp's code prints out the individual words in the array.
Re: Count Words in a String and Output First Four
Works great. Thanks all for your help.
Re: Count Words in a String and Output First Four
Oh. My bad. Just use the same statement for both scenario :
lineOfText[0]+" "+lineOfText[1]+" "+lineOfText[2]+" "+lineOfText[3]
Ksharp
Re: Count Words in a String and Output First Four
The problem with using lineOfText[0] + etc. for the scenario if numberOfWords is less than or equal to 4 is that lineOfText[1] or [2] or [3] may not exist. I think I got a compiler error when I tried this method.
Instead I used Arrays.toString(lineOfText)); and printed that. Works great.
Thanks again all for your help.
Re: Count Words in a String and Output First Four
Why use arrays?
Code:
String name = "vhonani";
if(name.length()< 4){
System.out.println("First four letters ");
for(int i=0;i<= name.length(); i++){
System.out.println(name.charAt(i));
}
System.out.println("Number of word is : " + name.length());
}
else if(name.length() >4){
System.out.println("First four letters ");
for(int i=0; i<=4; i++){
System.out.println(name.charAt(i));
}
System.out.println("Number of word is : " + name.length());
}
Re: Count Words in a String and Output First Four
@vhonanivb Did you test your code?
What happens when the String name has < 4 characters in it?
How many characters does it print when there are more than 4 characters in name?
Why does it print a message saying it will display 4 characters if there are less than 4?
Re: Count Words in a String and Output First Four
Additionally, don't spoonfeed code, and especially don't spoonfeed bad code. Code:
// if(name.length()< 4){
// for(int i=0;i<= name.length(); i++){
// etc
// }
// } else if(name.length() >4){
// for(int i=0; i<=4; i++){
// etc
// }
// }
for (int i = 0; i < 4 && i < name.length(); i++){
// etc
}
Quote:
Why does it print a message saying it will display 4 characters if there are less than 4?
And why does it print the first 5 characters if there are more than 4? Also, learn the meaning of "letter" and "word"
Finally, this thread was started more than a month ago. Don't post to dead threads.
db
Re: Count Words in a String and Output First Four
Code:
if(name.length()< 4){
System.out.println("First letters ");
for(int i=0;i<= name.length(); i++){
System.out.println(name.charAt(i));
}
System.out.println("Number of word is : " + name.length());
}
else if(name.length() >4){
System.out.println("First four letters ");
for(int i=0; i<4; i++){
System.out.println(name.charAt(i));
}
System.out.println("Number of word is : " + name.length());
}
I missed a couple of things in my code , but I still feel my code is more efficient than the use of an array.
Why use memory the is a way around it.
Re: Count Words in a String and Output First Four
It also doesn't work if the name length is exactly 4.
And will get an array index out of bounds exception if it's < 4.
Oh, and it's only printing the first 4 characters...the OP wanted the first 4 words hence the split() and the String[].
Re: Count Words in a String and Output First Four
Oh yes.
Sorry , I get it now.
Thanks