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

Untitled

By: a guest on May 2nd, 2012  |  syntax: None  |  size: 1.39 KB  |  hits: 14  |  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. //the very best pokemon trainer
  2. import java.util.Scanner;
  3.  
  4. public class PhraseCounter {
  5.         public static void main(String args[]) throws java.io.IOException {
  6.                 Scanner keyboard = new Scanner(System.in);
  7.                 boolean isDone = false;
  8.                 String search;
  9.                 int count = 0;
  10.                 String temp;
  11.                 String space = " ";
  12.                 System.out
  13.                                 .println("Enter some text to search in. Enter a blank line to stop.");
  14.                 temp = keyboard.nextLine();
  15.                 while (isDone == false) {
  16.                         String word = keyboard.nextLine();
  17.                         if (word.length() == 0)
  18.                                 isDone = true;
  19.                         temp = temp + space + word;
  20.  
  21.                 }
  22.                
  23.                 System.out.println("Enter a phrase to search the above text for: ");
  24.                 search = keyboard.nextLine();
  25.                 while(search.length() == 0){
  26.                         System.out.println("Please enter a non-blank phrase: ");
  27.                         search = keyboard.nextLine();
  28.                 }
  29.                 search = search.toLowerCase();
  30.                 search = search + space;
  31.                 temp = temp.toLowerCase();
  32.                 for (int i = 0; i < temp.length(); i++) {
  33.                         if (temp.charAt(i) == search.charAt(0)) {
  34.                                 for (int j = 0; j < search.length(); j++) {
  35.                                         if (temp.charAt(i + j) != search.charAt(j)) {
  36.                                                 break;
  37.                                         } else if (j == search.length() - 1) {
  38.                                                 count++;
  39.                                         }
  40.                                 }
  41.                         }
  42.                        
  43.                 }
  44.                 if (count == 1)
  45.                         System.out.print("The phrase " + search + " was found " + count
  46.                                         + " time.");
  47.                 else
  48.                         System.out.print("The phrase " + search + " was found " + count
  49.                                         + " times.");
  50.  
  51.         }
  52. }