簡體   English   中英

需要有關String Java的幫助

[英]Need help with String Java

我需要幫助以獲取長度大於等於用戶給定的最小長度的字符串數。 例如:字符串輸入“ this is a game” minlength =2。該句子中3個單詞的長度> =到minLength,因此輸出應為3。由於3個單詞> = minLength

我面臨輸出問題。 我輸入了一個字符串,將其拆分為單個單詞,然后將其發送給計算輸出的方法。上述示例的期望值為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();

    }

}

你很親密!

您為每個單詞調用LetterCount,並在LetterCount的開頭將countWords設置為0。因此,每次都會重置計數器!

在您的類中,countWords不能作為LetterCount的局部變量,而應作為私有變量。

地點

private static int countWords = 0;

在文件的頂部。

去掉

int countWords = 0;

來自LetterCount。

這是因為您每次都只將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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM