Need help with String Java
I need help with getting the number of strings whose length is >= to a minlength given by the user. ex: the string input "this is a game" minlength = 2. the length of 3 words in that sentence is >= to minLength so the output should be 3. Since 3 words are >= the minLength
I facing a problem with the output. I inputing a string, splitting it apart into individual words and sending them to method which compute the output.. The desired for the above example is 3 but i m getting 1,1,1.
public class WordCount {
/**
* @param args
*/
public static String input;
public static int minLength;
public static void Input() {
System.out.println("Enter String: ");
input = IO.readString();
System.out.println("Enter minimum word length: ");
minLength = IO.readInt();
}
public static void Calc() {
Input();
String[] wor开发者_高级运维ds = input.split(" ");
for (String word : words) {
LetterCount(word);
}
}
public static int LetterCount(String s) {
int countWords = 0;
if (s.length() >= minLength) {
countWords += 1;
IO.outputIntAnswer(countWords);
}
return countWords;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Calc();
}
}
You are very close!
You call LetterCount for each word, and at the start of LetterCount you set countWords to 0. Therefore, your counter is reset every time!
Have countWords not as a local variable to LetterCount, but a private variable in your class.
Place
private static int countWords = 0;
at the top of the file.
Remove
int countWords = 0;
from LetterCount.
Its because you're only reseting the countWords variable every time to zero and outputting 1. Make a static integer to hold the count, and call your output function in calc
after you've literated over all the strings.
static int countWords = 0;
public static void Calc() {
Input();
String[] words = input.split(" ");
for (String word : words) {
LetterCount(word);
}
IO.outputIntAnswer(countWords);
}
public static int LetterCount(String s) {
if (s.length() >= minLength) {
countWords += 1;
}
return countWords;
}
You are setting countWords=0 every time you enter LetterCount() You should remove counting logic from LetterCount() and put it in Calc() around the loop.
精彩评论