简体   繁体   中英

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 im 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[] 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!

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;
}

每次输入LetterCount()时都要设置countWords = 0。应该从LetterCount()中删除计数逻辑,并将其放在循环中的Calc()中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM