Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 1.89 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import java.util.Scanner;
  2.  
  3.     public class Main
  4.     {
  5.        public static void main(String args[])
  6.        {
  7.           Scanner kb = new Scanner(System.in);
  8.           int count = 0;
  9.  
  10.           boolean good = false;
  11.          
  12.           String phrase;
  13.           String text;
  14.            
  15.           System.out.println("Enter some text to search in. Enter a blank line to stop.");
  16.           text = kb.nextLine();
  17.  
  18.  
  19.           while (good == false)
  20.           {
  21.              String word = kb.nextLine();
  22.              if (word.length() == 0)
  23.              {
  24.                good = true;
  25.              }
  26.              text += word;
  27.           }
  28.  
  29.           System.out.print("Enter a phrase to search the above text for: ");
  30.           phrase = kb.nextLine();
  31.  
  32.           while (phrase.length() < 1)
  33.           {
  34.              System.out.print("Please enter a non-blank phrase: ");
  35.              phrase = kb.nextLine();
  36.           }
  37.  
  38.           String phrase1 = phrase.toLowerCase();
  39.           String text1 = text.toLowerCase();
  40.  
  41.           for (int cntr1 = 0; cntr1 < text.length(); cntr1++)
  42.           {
  43.              if (text1.charAt(cntr1) == phrase1.charAt(0))
  44.              {
  45.                 for (int cntr2 = 0; cntr2 < phrase.length(); cntr2++)
  46.                 {
  47.                    if (text1.charAt(cntr1 + cntr2) != phrase1.charAt(cntr2))
  48.                    {
  49.                       break;
  50.                    }
  51.                    else if (cntr2 == phrase1.length() - 1)
  52.                    {
  53.                       count++;
  54.                    }
  55.                 }
  56.              }
  57.           }
  58.  
  59.           if (count == 1)
  60.           {
  61.              System.out.println("The phrase \"" + phrase +  "\" was found " + count + " time.");
  62.           }
  63.           else
  64.           {
  65.              System.out.println("The phrase \"" + phrase +  "\" was found " + count + " times.");
  66.           }
  67.        }
  68.     }