我在完成这个编程作业时遇到问题...(这是家庭作业) 该程序的目标是在输入文件中查找所有 7 位电话号码,并找到它们可能组成的单词(例如 1 = a/b/c...),然后在文本文件中查找它们,看看它们是否是正确的单词。到目前为止,我的程序似乎运行良好,当我在递归函数中放入 println 语句时,我看到了我期望的所有结果。然而问题是,我看到一个打印的单词,例如“cat”,即使它存在于查找文件中,它也不会打印它。抱歉,如果这是一个不好的描述。我附上了我的程序代码。
谢谢, 附:我已经查看了与我的问题类似的其他线程,但它们没有帮助。
import java.io.*;
import java.util.*;
public class PhoneWords
{
public static void main(String[] args) throws IOException
{
PrintWriter fstream = new PrintWriter(new FileWriter("output.txt"));
Scanner numbers = new Scanner(new File("telephones.txt"));
Scanner words = new Scanner(new File("words.txt"));
String current = "";
while(numbers.hasNext())
{
current = numbers.next().toLowerCase();
current = current.replaceAll("-", "");
fstream.println(toWordString("", current, words));
System.out.println(toWordString("", current, words));
}
fstream.close();
numbers.close();
words.close();
}
public static String toWordString(String word, String number, Scanner ifstream)
{
char[] guess = new char[3];
if(number.length() == 0)
{
if(isFound(word, ifstream))
{
System.out.println(word);
return number + word;
}
}
else
{
guess = getPossibleLetters(number.charAt(0));
number = number.substring(1);
toWordString(word + guess[0], number, ifstream);
toWordString(word + guess[1], number, ifstream);
toWordString(word + guess[2], number, ifstream);
}
return number + ": None";
}
public static boolean isFound(String word, Scanner ifstream)
{
String current = "";
//System.out.println(word);
while(ifstream.hasNext())
{
current = ifstream.next();
if(current.equalsIgnoreCase(word))
return true;
}
return false;
}
public static char[] getPossibleLetters(char c)
{
switch(c)
{
case '0':
case '1':
throw new NumberFormatException("Digit cannot be 0 or 1");
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', 'r', 's'};
case '8':
return new char[] {'t', 'u', 'v'};
default:
return new char[] {'w', 'x', 'y'};
}
}
}
最佳答案
我认为您的代码中存在以下问题:
1、你看到找到的单词打印出来但在输出文件中看不到它的原因是你没有处理递归调用toWordString
函数的返回值,下面 block 中的返回值返回到上层toWordString
而不是main
函数:
if(isFound(word, ifstream))
{
System.out.println(word);
return number + word;
}
您应该处理对 toWordString
函数的 3 次递归调用的返回值,或者为 toWordString
添加一个额外的参数(如 List)来保存递归调用之间的返回结果。
2,您不应使用 Scanner ifstream
作为 toWordString
的参数,对 toWordString
的递归调用使用相同的 Scanner 对象,并且第一次调用 isFound
将迭代扫描器中的所有 token ,对 isFound
的进一步调用将始终返回 false
您最好在 main
函数中将所有单词读入集合中,然后将集合传递给 toWordString
关于java - 递归打印电话号码中可能的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028625/