I already have the code for the assignment below, but there are some errors in the code. Please help me fix the code. The assignment: Continue Exercise •• P13.1, checking the words against the /usr/share/dict/words on your computer, or the words.txt file in the companion code for this book. For a given number, only return actual words.
I already have the code for the assignment below, but there are some errors in the code. Please help me fix the code.
The assignment: Continue Exercise •• P13.1, checking the words against the /usr/share/dict/words on your computer, or the words.txt file in the companion code for this book. For a given number, only return actual words.
The code of resource class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class U10P02R
{
static ArrayList<String> words = new ArrayList<String>();
U10P02R(){
try {
File myObj = new File("words.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
words.add(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
// This method to returns a character array containing all possible keypad
// encodings for a digit in a standard phone
char[] keysForButton(int n) {
switch (n) {
case 0:
return new char[] { ' ' };
case 1:
return new char[] { '.' };
case 2:
return new char[] { 'A', 'B', 'C' };
case 3:
return new char[] { 'D', 'E', 'F' };
case 4:
return new char[] { 'G', 'H', 'I' };
case 5:
return new char[] { 'J', 'K', 'L' };
case 6:
return new char[] { 'M', 'N', 'O' };
case 7:
return new char[] { 'P', 'Q', 'R', 'S' };
case 8:
return new char[] { 'T', 'U', 'V' };
case 9:
return new char[] { 'W', 'X', 'Y', 'Z' };
}
return null;
}
public void testProg()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter pin number: ");
String n = sc.nextLine();
System.out.println("All possible spellings for " + n + ":");
U10P02R r = new U10P02R();
r.getSpellings(n);
}
public void getSpellings(String n) {
if (n != null)
getSpellings(n, "");
}
public boolean checkSpelling(String spell) {
return words.contains(spell);
}
public void getSpellings(String n, String txt) {
if (n.length() == 0) {
if(checkSpelling(txt))
System.out.println(txt);
} else {
int digit = n.charAt(0) - '0';
char letters[] = keysForButton(digit);
if (letters != null) {
for (int i = 0; i < letters.length; i++) {
//appending the current letter to the txt and calling the
//recursive method by removing 0th character from string 'n'
getSpellings(n.substring(1), txt + letters[i]);
}
}
}
}
}
The code of the driver class:
public class U10P02D
{
public static void main (String [] args)
{
U10P02R t = new U10P02R();
t.testProg();
}
} //end driver class
The errors are shown in the picture I attached
Trending now
This is a popular solution!
Step by step
Solved in 3 steps with 5 images