我已经编写了这个方法countToken
,它以Scanner s
和String t
为参数,并返回一个int。它返回t作为s中的令牌出现的时间。这是我所能做的,对我来说是有意义的,但它不能正常工作。
public static int countToken(Scanner s, String t)
{
int count = 0;
while (s.hasNext()==true)
{
if (s.next()==t)
{
count++;
}
}
return count;
}
所以这是我在阅读了所有评论和建议后得出的结论。让我知道你对的看法
public static int countToken(Scanner s, String t)
{
int count=0;
String token="";
while (s.hasNext())
{
token = s.next();
if(token.equals(t))
{
count++;
}
else
{
}
}
return count;
}
试试这个:
countToken(new Scanner("The book is the give the"), "the");
这里Scanner
包含"书是给予"和token t
是"。所以我们必须计算Scanner s
中出现了多少""。
public static int countToken(Scanner s, String t)
{
int count = 0;
while (s.hasNext())
{
String word=s.next();
if (word.toLowerCase().equals(t.toLowerCase()))
{
count++;
}
}
return count;
}
输出:3