我想统计“用户”输入的数组中出现的次数并将其存储在变量中命名为“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循环的括号,并将'the'前面的空格拆分 – Yazan
如果split()导致字符串被拆分,你已经知道“the”已被找到。只需输出“input.length - 1”作为“the”的计数。无需循环。 –