2013-06-20 127 views
-2

對不起,我對我的程序非常困惑,我試圖調用一個方法,該方法返回一個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; 
     } 

} 
+2

你能告訴我們你有什麼錯誤嗎?順便說一下,爲什麼不使用'equals'而不是檢查所有字符是否相等?... – Maroun

+0

對不起,我正在收到錯誤:找不到符號 \t \t checkMatchesSomewhere(secretword,guessword); //在secretWord中 \t \t^ 符號的地方檢查匹配數量:可變secretWord中 位置:類應用 對我所說的方法CheckMatchesSomewhere(...) –

+0

我會強烈建議在開始一個良好的入門書行Java或Oracle的教程。這裏有很多問題都表明你對絕對基本知識並沒有一個牢固的把握。 –

回答

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. 

終於請到通過Basics of java

+0

是的,使用調試器會幫助他很多。 – Maroun

+1

這是他的一個*問題,是的。 –

+0

就是這樣。乾杯。 –

0

你不應該在checkMatchesSomewhere方法聲明secretWordguessWord變量,因爲它們已經方法的參數另外你是不是將該方法的結果分配給secretMatches,以便始終報告零匹配。

編輯:只是注意到你已經使用了不同的方法參數的情況。我猜這可能不是有意的。

+0

當然,非常感謝! –

0

我不知道你的邏輯,但commen意識說,當參數傳遞給一個方法,他們應該被用來代替創建新的。

您正在將參數傳遞給checkMatchesSomewhere()但未使用它們。

相關問題