我有一个任务是从 7 位电话号码生成每个可能的单词,并使用 PrintWriter 将其保存为 .txt 文件。我的代码在下面,但我的输出(目前只是打印到控制台)是相同的 3 个“单词”2187 次。
package ks2_Lab19;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class WordGenerator {
private static String[] two = {"a", "b", "c"};
private static String[] three = {"d", "e", "f"};
private static String[] four = {"g", "h", "i"};
private static String[] five = {"j", "k", "l"};
private static String[] six = {"m", "n", "o"};
private static String[] seven = {"p", "r", "s"};
private static String[] eight = {"t", "u", "v"};
private static String[] nine = {"w", "x", "y"};
private static char[] numArray;
private static String[] wordList = new String[2187];
public static void convert(char[] input){
for (int i = 0; i < 2184; i = i + 3){
for (int a = 0; a < 7; a++){
for (int b = 0; b < 3; b++){
if (input[a] == '1' || input[a] == '0') {
wordList[i+b] = wordList[i+b] + " ";
}//if 0 or 1
if (input[a] == '2'){
wordList[i+b] = wordList[i+b] + two[b];
}//if 2
if (input[a] == '3'){
wordList[i+b] = wordList[i+b] + three[b];
}//if 3
if (input[a] == '4'){
wordList[i+b] = wordList[i+b] + four[b];
}//if 4
if (input[a] == '5'){
wordList[i+b] = wordList[i+b] + five[b];
}//if 5
if (input[a] == '6'){
wordList[i+b] = wordList[i+b] + six[b];
}//if 6
if (input[a] == '7'){
wordList[i+b] = wordList[i+b] + seven[b];
}//if 7
if (input[a] == '8'){
wordList[i+b] = wordList[i+b] + eight[b];
}//if 8
if (input[a] == '9'){
wordList[i+b] = wordList[i+b] + nine[b];
}//if 9
}//possible output for loop
}//input array for loop
}//write to wordList for loop
}
public static void main(String[] args) {
//initialize output file name and PrintWriter object
String fileName = "output.txt";
PrintWriter outputStream = null;
String output = "";
//try and catch exception
try {
outputStream = new PrintWriter(fileName);
}
catch (FileNotFoundException e){
System.out.println("Error opening file " + fileName + ".");
System.exit(0);
}
//initialize scanner and wordList array
Scanner kb = new Scanner(System.in);
for (int i=0; i < 2187; i++){
wordList[i] = "";
}
//announce and accept input
System.out.println("Please input a 7 digit phone number without special characters.");
String num = kb.next();
numArray = num.toCharArray();
convert(numArray);
for (int p = 0; p < 2187; p++){
System.out.println(wordList[p]);
}
}
}