• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

plz correct code

 
prathimaprasun rao
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,
I have to read a question from command line. Then I need to count the number of words and display the number of words as output. This is the code I have written. But I am not able to get the output. Cud anyone correct the code.

import java.io.*;
public class wordcount {
private static long countWords(String line) {
long numWords = 0;
int index = 0;
boolean prevWhitespace = true;
while (index < line.length()) {
char c = line.charAt(index++);
boolean currWhitespace = Character.isWhitespace(c);
if (prevWhitespace && !currWhitespace) {
numWords++;
}
prevWhitespace = currWhitespace;
}
return numWords;
}


public static void main(String[] args ) throws IOException{
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
if (args.length == 0) {
countWords("stdin");
} else {
for (int i = 0; i < args.length; i++) {
countWords(args[i]);
}
}
}
}


Eagerly waiting for reply.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you not allowed to use other methods in the String class? Starting in 1.4 there is a method that could do that in one line.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your "countWords" method is returning a value, but your main() method is just ignoring it. main() should use, e.g., System.out.println() to actually display the result of calling the method.
 
prathimaprasun rao
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello everyone,

could anyone clearly explain where the error is?

thanks in advance.
 
prathimaprasun rao
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Keith Lynn

could you please write the code for me how to do this in a single line.
the main idea is i need to read one sentence from command line and display the number of words present in it

thanks in advance
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
could you please write the code for me how to do this in a single line

No. This is an assignment that is supposed to teach you something. How are you going to learn if someone else does the work for you?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Ulf. If you read through the API for String, you will see several useful methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic