我想統計「用戶」輸入的數組中出現的次數並將其存儲在變量中命名爲「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」的計數。無需循環。 –