我正在尝试识别两个电话号码的相似数字。
这两个电话号码的相似数字是1 3 4 5 6。
class yolo1{
public static void main (String args[]){
String telUDM="5143436111", telJean="4501234567";
Integer i=0;
for(i=0;i<telUDM.length();i++){
for (j=0;j<telJean.length();j++){
if(telUDM.indexOf(i)== telJean.indexOf(j)){
System.out.println()/*I am stuck here and do not know what to do from here*/
}}}
答案 0 :(得分:1)
尝试使用sets:
String telUDM = "5143436111";
String telJean = "4501234567";
Set<Character> tel1 = new HashSet<Character>();
for (char c : telUDM.toCharArray())
tel1.add(c);
Set<Character> tel2 = new HashSet<Character>();
for (char c : telJean.toCharArray())
tel2.add(c);
tel1.retainAll(tel2);
List<Character> answer = new ArrayList<Character>(tel1);
Collections.sort(answer);
System.out.println(answer);
=> [1, 3, 4, 5, 6]
答案 1 :(得分:0)
你解决问题的方法有点不对劲;你正在使用.charAt()的循环索引。如果我使用你的方法:
12356 73925
它检查1和7,2和3,3和9,5和2,6和5.它应该检查1和73295,2和73925等。
由于你的方法让你看起来想要使用循环,我建议在循环中循环,如下所示:
`for(i=0;i<telUDM.length();i++){
for(y = 0; y < telJean.length(); y++) {
// I'll leave the solution to you.
//use an Array int[] myArray to add the numbers you want to print
System.out.println(myArray);`
} }
答案 2 :(得分:0)
试试这个......
for (int x=0; x<telUDM.length(); x++)
{
for (int y=0; y<telJean.length(); y++)
{
if (telUDM.charAt(x) == telJean.charAt(y))
System.out.print(telUDM.charAt(x) + " "); //See comments below
}
}
因为如果数字是相同的,只需打印一个即可。