我想製作一個程序,它需要一組數字(如234),並且此時可以打印手機鍵盤上可能存在的每個字母組合。用於文本的遞歸編程預測文本
(1 - 什麼都沒有,2 - ABC,3高清等)
我目前有:
import java.util.*;
public class testCombo {
static String str="217";
static ArrayList<String> list=new ArrayList<String>();
static void addLet(String seg){
if(seg.length()==str.length()){
list.add(seg);
return;
}
char currentChar=str.charAt(seg.length());
if(currentChar==1 || currentChar==0)
{
String str1=seg+" ";
addLet(str1);
}
if(currentChar=='2'){
addLet(seg+"a");
addLet(seg+"b");
addLet(seg+"c");
}
else if(currentChar=='3'){
addLet(seg+"d");
addLet(seg+"e");
addLet(seg+"f");
}
else if(currentChar=='4'){
addLet(seg+"g");
addLet(seg+"h");
addLet(seg+"i");
}
else if(currentChar=='5'){
addLet(seg+"j");
addLet(seg+"k");
addLet(seg+"l");
}
else if(currentChar=='6'){
addLet(seg+"m");
addLet(seg+"n");
addLet(seg+"o");
}
else if(currentChar=='7'){
addLet(seg+"p");
addLet(seg+"q");
addLet(seg+"r");
addLet(seg+"s");
}
else if(currentChar=='8'){
addLet(seg+"t");
addLet(seg+"u");
addLet(seg+"v");
}
else if(currentChar=='9'){
addLet(seg+"w");
addLet(seg+"x");
addLet(seg+"y");
addLet(seg+"z");
}
}
public static void main(String[] args){
addLet("");
for(String str:list) //Sets str to each value in list during each iteration
System.out.println(str);
}
}
我的代碼,我們應該使用遞歸編程,但我不能讓它爲1s和0s工作。 (這只是一個練習課,我有另一個允許用戶輸入,它已經驗證它只包含數字)
這種方式發現然後打印出每個組合計數爲遞歸?
正在做作業嗎? – bramp 2010-09-06 09:57:25
爲什麼你爲每個字符串聲明一個新的變量,然後你只是將它用作'addLet'的參數?爲什麼不使用'addLet(seg +「x」)'等? – 2010-09-06 09:59:24
嗯是啊,我沒有考慮這樣做,這樣做很有意義;/ – Admiration 2010-09-06 10:07:07