2013-12-23 30 views
2

为什么我会像返回数据那样得到差异。它工作正常,直到3,然后繁荣,它一直到最后。我所做的很简单。我从带有id,name的txt文件中获取值,并将id与另一个具有名称,名称的txt文件进行匹配,使其看起来像id,id,如下所示。但是,它不会像你所期望的那样工作。匹配正在进行得很好,直到它弄糟了。为什么我的代码在几个阶段返回不正确的键?

0,1 
1,3 
0,2 
0 
3,0,4 
2 
3,0 
4,2 
4,1 
2, 




while ((output2 = br2.readLine()) != null) { 

    String[] vv = output2.split(","); 
    String value1 = vv[0]; 
    String value2 = vv[1]; 

    for (Map.Entry<Integer, String> entry : map.entrySet()) { 
     int key = entry.getKey(); 
     String value = entry.getValue(); 
            //System.out.println(key+","+value); 

     if ((value1.equals(value))) { 
      System.out.print(key + ","); 

     } 

     if ((value2.equals(value))) { 
      System.out.print(key + "\n"); 
     } 

    } 

} 

数据

ids.txt 

0,Triple H 
1,John Cena 
2,Megan Fox 
3,The Undertaker 
4,Pamela Anderson 
5,The Rock 

的text.txt

Triple H,John Cena 
John Cena,The Undertaker, 
Triple H,Megan Fox 
The Undertaker,Triple H 
+0

你可以把2个txt文件放在这里(只是第一条线)吗? – CtrlX

+0

嘿,我做到了。检查编辑。 –

+0

虽然这不能解决您的问题,但请记住,您可以只使用if(vv [0] .equals(value))而不是使变量名称为value1并检查等价。 – Chronicle

回答

6

你的第四个条目

String value2 = vv[1]; 

vv[1]将null作为有第一个逗号之后没有价值。

编辑:

在第四条目

The Undertaker,Triple H 

value2 (i.e. Triple H)在循环中的zeroth positionfirst iteration匹配,所以它是印有\n, 然后entry 3 is matched4rd iteration,它是印在next line with a comma

这就是为什么你得到输出像

0 
3,0,4 
+0

检查编辑。谢谢 –

+0

@AliGajani检查编辑 – gaurav5430

+0

如何解决?兄弟。 –

1

看起来像一个简单的解决方案将持有匹配的值,直到for循环后。

while ((output2 = br2.readLine()) != null) { 
    String[] vv = output2.split(","); 
    String value1 = vv[0]; 
    String value2 = vv[1]; 
    int key1 = -1; 
    int key2 = -1; 

    for (Map.Entry<Integer, String> entry : map.entrySet()) { 
     int key = entry.getKey(); 
     String value = entry.getValue(); 
            //System.out.println(key+","+value); 

     if ((value1.equals(value))) { 
      key1 = key; 
     } 

     if ((value2.equals(value))) { 
      key2 = key; 
     } 

    } 
    if (key1 != -1 && key2 != -1) { 
     System.out.println(key1 + ", " + key2 + "\n"); 
    } 
} 
+0

给我一个错误ryknow。无法从int转换为null。 –

+0

嘿,我用两个循环修复了它 –

+0

我的错误。你必须使用Integer或者将它设置为一个你不会有-1的id的值。 – ryknow

相关问题