[英]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
例如:字符串输入“ this is a game” minlength =2。该句子中3个单词的长度> =到minLength,因此输出应为3。由于3个单词> = 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 im getting 1,1,1.
我输入了一个字符串,将其拆分为单个单词,然后将其发送给计算输出的方法。上述示例的期望值为3,但即时得到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[] words = 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! 您为每个单词调用LetterCount,并在LetterCount的开头将countWords设置为0。因此,每次都会重置计数器!
Have countWords not as a local variable to LetterCount, but a private variable in your class. 在您的类中,countWords不能作为LetterCount的局部变量,而应作为私有变量。
Place 地点
private static int countWords = 0;
at the top of the file. 在文件的顶部。
Remove 去掉
int countWords = 0;
from LetterCount. 来自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. 这是因为您每次都只将countWords变量重置为零并输出1。创建一个静态整数来保存该计数,并在对所有字符串进行了
calc
之后在calc
调用输出函数。
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;
}
每次输入LetterCount()时都要设置countWords = 0。应该从LetterCount()中删除计数逻辑,并将其放在循环中的Calc()中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.