【发布时间】:2013-11-16 13:52:48
【问题描述】:
我有一个任务是从 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]);
}
}
}
【问题讨论】:
-
“我们班一直有在教我们新主题之前先测试我们的趋势”——在 SO 上请其他人帮助你这不算作作弊吗?跨度>
-
@Jongware 恕我直言,我认为,OP 已经做出了一些努力,并且在一些困难的情况下寻求帮助,所以它不是作弊。 OP 正在努力加入 SO 并获得有关逻辑的帮助/指导。指导他是我们的责任,但请确保不要给他完整的代码。 :)
-
@Jongware 如果我们中的一个人只是写作业并将其交给他/她,那么是的,那将是作弊。然而,通过适当地展示努力并寻求指导,这更像是去找导师寻求帮助。至少我是这么看的
-
我认为这个赋值的目的是为了说明递归——你的最终循环会尝试最后一个字符的所有可能字符,对吧?如果您编写了一个能够将其作为结束案例的方法,您应该能够对其进行扩展并调用它,直到它最终获得其结束案例,因此您的代码不需要这三个循环(我不需要确定循环正在做什么,因为索引或计算没有被评论,也没有有意义的名称)。
标签: java phone-number