【发布时间】:2016-11-20 07:00:05
【问题描述】:
我想计算“the”在我根据用户输入创建的标记数组中出现的次数,并将其存储在名为“theCount”的变量中。我正在使用 for 循环遍历数组并使用 if 语句检查“the”。
我不允许使用正则表达式。
这是我目前所拥有的:
import java.util.*;
public class theCount
{
public static void main (String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = userInput.nextLine();
String[] input = sentence.split(" the");
int theCount = 0;
for (String token : input) {
if (token == "the")
theCount++;
System.out.print("\n" + theCount); //I want it printed after
//iteration.
}
}
}
【问题讨论】:
-
将
System.out.print...移出for loop括号,the之前的空格应该在split中删除 -
如果
split()导致字符串被拆分,则您已经知道“the”已找到。只需打印input.length - 1作为“the”的计数。不需要循环。
标签: java arrays if-statement token