-2

我需要你的帮助来建议我的代码哪里出错了。实际上,我想要的是使用文档对形成集群。我的文本文件中有近 1000 对数字,因此它必须将第一对作为输入并将其存储在一个数组中,现在它应该采用第二对并检查是否存在任何一个元素。如果数组中只存在一个元素,则必须将另一个元素添加到同一个数组中。如果这两个元素都不存在于数组中,则必须将它们存储在新数组中。

样本输入:
(23,7)
(11,23)
(1,5)
(67,5)
(34,17)

输出:
(23,7,11)
(1,5,67)
(34,17)

我的问题是我无法从文本文件中获取输入,因为它是整数,但要拆分文本文件,它应该是字符串。我的第二个问题是我无法将它存储在另一个数组中。声明数组后,元素将被覆盖。dis 是我编写的代码,用于将数字存储在数组列表中,但我无法将元素存储在另一个数组中,我不知道在哪里声明新的数组列表

ArrayList a = new ArrayList();
a.add(i);
a.add(j);
if (!a.contains(i) && !a.contains(j))
{
    a.add(i);
    a.add(j);
    System.out.println("the cluster is" +a);
}
else if(a.contains(i) && !a.contains(j))
{
    a.add(j);
    System.out.println("the cluster is" +a);
}
else if(!a.contains(i) && a.contains(j))
{
    a.add(i);
    System.out.println("the cluster is" +a);
}
4

1 回答 1

0

1)它们是整数并不重要。为此,您上面的“i”和“j”变量可以是字符串。2)您的单个 ArrayList 将永远不会保存此类信息。有一些选项需要考虑,但最直接的方法是 array-of-arrays: ArrayList<ArrayList<String>> pairs = new ArrayList<ArrayList<String>> ();。在这种情况下,外部列表的每个元素都是一个字符串数组 - 与您想要的输出相同。然后,您的代码将看起来更像这样:

// For each inner array in the outer array,
//    check to see if it contains either, neither, or both of i or j 
//    If it contains one, add the other to the inner array
//    Else if it contains neither, make a new array of strings and add that to the outer array

试试看,如果你再次卡住,回来问。

于 2013-03-28T16:46:44.377 回答