samedi 19 novembre 2016

how do I split a word in a string into two tokens if it contains a smaller word

I want to count the number of times "the" shows up in an array of tokens I made from user input and store it in a variable named "theCount". I'm iterating through the array with a for loop and checking for "the" with an if statement.

I am not allowed to use regular expressions.

This is what I have so far:

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. 

        }




    }


}

Aucun commentaire:

Enregistrer un commentaire