这是我过去未能及时完成的作业。我是一名新程序员,正在努力解决字符搜索程序的这种方法。我一直困惑于 if 语句使用哪个 boolean 逻辑,以及如何使用预定义的字符变量在短语中查找匹配项。示例测试是:character = "x",phrase = "Xerox"。而 X 和 x 是不同的。预期输出应为 count = 1。 编辑:这个问题应该在不使用数组或列表的情况下得到回答。
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
Scanner jf = new Scanner(phrase);
count = 0;
for (int i = phrase.length(); i > 0; i--)
{
jf.findInLine(character);
if(jf.hasNext())
{
count++;
jf.next();
}
}
return count;
}
最佳答案
给你:
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
int count = 0;
// for every character in phrase ...
for (int i = 0; i < phrase.length(); i++)
{
// ... if it is the right one ...
if(phrase.charAt(i) == character)
{
// ... increment the counter
count++;
}
}
return count;
}
您不需要任何扫描仪,并且代码相当简单、可读且易于理解。
关于java - java中循环迭代时如何计算特定字符串是否匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29399837/