抱歉,我对我的程序非常困惑,我试图调用一个返回int的方法,但是我要将其传递给字符串变量。我已经在方法中使用了代码,但现在已经将它移动到我希望用checkMatchesSomewhere()调用的方法中。
我想将String变量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;
}
}
答案 0 :(得分: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
答案 1 :(得分:0)
您不应在secretWord
方法中声明guessWord
和checkMatchesSomewhere
变量,因为它们已经是方法参数,另外您没有将方法的结果分配给{{1所以它总会报告零匹配。
答案 2 :(得分:0)
我不知道你的逻辑,但是commen意义上说当参数传递给方法时,应该使用它们而不是创建新的。
您正在将参数传递给checkMatchesSomewhere()但未使用它们。