Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Predictive text (Cell phone)


[code]import java.io.*;
import java.util.*;

class HomeWork1{
static String[]list = new String[100];
public static void main(String[] args)throws IOException{
 
Scanner in = new Scanner (new FileReader("input.txt"));
PrintWriter out = new PrintWriter (new FileWriter("output.txt"));

String []num = new String[100];
  int z = 0;
   String str = in.next();

      while(!(str.equals("$$$$"))){            
       list[z] = str;
       num[z] = getWord(str);
       z++;
       str = in.next();
      }

insertionSort(list,0,z);
for(int i = 0; i < z; i++){
System.out.println(list[i]);
}
for(int i = 0; i < z; i++){
System.out.println(num[i]);
}


in.close();
out.close();
}//main

public static void insertionSort(String[]list,int lo, int n){
  for(int j = lo+1; j < n; j++){
   String key = list[j];
   int k = j-1;
   while(k >= lo && key.compareToIgnoreCase(list[k]) < 0){
    list[k + 1] = list[k];
    --k;
   }//end while
   list[k+1] = key;
   }//end for
}//end insertion sort


public static int binarySearch(int[]arr, int lo, int hi,int key){
  while(lo<=hi){
   int mid = (lo + hi)/2;
   if(key ==arr[mid])return mid;
   if(key < arr[mid])hi = mid - 1;
   else lo = mid + 1;
  }//end while
  return -1;
}//end binarysearch

 
  public static String getWord(String word){
  int l = word.length();
  String str = " ";
  for(int i = 0; i < l; i++){
  
   char y = word.charAt(i);
   if(y=='a'||y=='b'||y=='c')
   {
    str +=  2;
   }
    if(y=='d'||y=='e'||y=='f'){
      str += 3;
    }
    if(y=='g'||y=='h'||y=='i'){
      str += 4;
    }
    if(y=='j'||y=='k'||y=='l'){
      str += 5;
    }
   
    if(y=='m'||y=='n'||y=='o'){
      str += 6;
    }
   
    if(y=='p'||y=='q'||y=='r'|| y=='s'){
      str += 7;
    }
    if(y=='t'||y=='u'||y=='v'){
      str += 8;
    }
   
    if(y=='w'||y=='x'||y=='y'||y=='z'){
      str += 9;
    }
   
  }
  //System.out.println(str);
  return str;
}//end get word    
}//class

Some sample input:
Pale choose chosen called move
predictive TEXT mobile
Phone Spell Message Note SaKe
$$$$
6683
7253
37549
662453
0

Sample output:
6683
move Note

7253
Pale SaKe

37549
No words found in dictionary

662453
mobile

I am to read the foregoing file and produce the above output using ‘predictive text’ mode. The point is when I press 7 2 5 3 – each digit once and the phone will try and figure out which word you want. If there are several possibilities, it will allow you to choose the one you want. In this example, possible words are pale, rake, sake and sale. The phone uses a dictionary to decide which combinations of letters are valid.