-3

抱歉,我对我的程序感到非常困惑,在该程序中,我试图调用一个返回 int 的方法,但我想将其传递给字符串变量。我已经让该方法中的代码正常工作,但现在已将其移至我希望使用 checkMatchesSomewhere() 调用的自己的方法中。

我想将字符串变量secretWord 和secretGuess 的值传递给该方法,以便它们可以在循环中使用。但它没有编译。有人可以告诉我我做错了什么吗?非常感谢。我是编程新手。

class App
{
    public static void main(String args[])
    {
        App app = new App();
    }
    //constructor
    public App()

    {

        //variables

        String secretWord = "berry";
        String guessword = "furry";
        secretMatches = 0;

                //Call CheckMatchesSomewhere method
        checkMatchesSomewhere(secretword, guessword); // checks number of matches somewhere in the secretWord

        // print the number of times the secretChar occurs in the string word
        System.out.println(secretMatches);

    }

    // METHOD THAT CHECKS FOR NUMBER OF MATCHES SOMEWHERE IN THE WORD

        private int checkMatchesSomewhere(String secretword, String guessword)

        {
        // variables
        String secretWord;
        String guessWord;
        int secretMatches = 0;

        //check each letter in sequence against the secretChar
        //
        //a loop which reads through 'secretWord'
        for (int j = 0; j < secretWord.length(); j++)
        {

            //the loop which goes through 'word'
            for (int i = 0; i < guessWord.length(); i++)
            {
                if (guessWord.charAt(i) == secretWord.charAt(j))
                {
                    secretMatches++;

                    //break once a match is found anywhere
                    break;
                }

            } // end word for loop

        } // end secretWord for loop

        // return the number of matches somewhere
        return secretMatches;
        }

} 
4

3 回答 3

1

您的代码中至少有 10 个错误。其中一些错误。

 secretMatches = 0;  //where is the datatype ??  

它应该是 int secretMatches = 0;

Java 区分大小写。

String secretWord = "berry";  //you declared like this

 checkMatchesSomewhere(secretword, guessword);  //secretWord  should pass here 

  String secretWord = null;// you have  to intialize it.
 String guessWord = null; // you have  to intialize it.

最后请阅读Java 基础知识

于 2013-06-20T15:23:43.570 回答
0

您不应该在方法中声明secretWordandguessWord变量,checkMatchesSomewhere因为它们已经是方法参数,另外您没有将方法的结果分配给,secretMatches因此它将始终报告零匹配。

编辑:刚刚注意到您对方法参数使用了不同的大小写。我猜这可能不是故意的。

于 2013-06-20T15:24:00.850 回答
0

我不知道你的逻辑,但常识说当参数传递给一个方法时,应该使用它们而不是创建新的。

您正在将参数传递给 checkMatchesSomewhere() 但没有使用它们。

于 2013-06-20T15:32:25.513 回答