我需要定位并列出数组中所有重复的索引值。
例如: int[] array = { 0, 7, 9, 1, 5, 8, 7, 4, 7, 3};
数字7在索引1、6和8处出现了三次。如何修改现有代码,以便使outputResults.setText()显示重复值的位置?如果有帮助,outputResults.setText()是JTextField。
String tmp1 = getNumbers.getText();
try {
int search = Integer.parseInt(tmp1);
for (p = 0; p < array.length; p++) {
if(array[p]==search) {
b = true;
index = p;
}
}
if(b==true)
outputResults.setText(search + " was in the following fields of the array " + index);
else
throw new NumberNotFoundException("Your number was not found.");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(getContentPane(), "You can only search for integers.");
} catch (NumberNotFoundException ex) {
JOptionPane.showMessageDialog(getContentPane(), ex.getMessage());
}
在目前的状态下,它只会列出重复数字最后一次被定位的位置,根据我的示例是索引8。数组中的数字列表由用户输入,并且我不允许对这些值进行排序。我的最初想法是创建一个嵌套循环,每当它找到一个重复的数字时,就将p(当前正在搜索的索引)添加到一个新数组中。然后,我会在outputResults.setText()中列出完整的数组,但是当我尝试时,它给出了多个警告和错误。
如果需要,可以在此处找到完整代码:http://pastebin.com/R7rfWAv0 是的,完整程序很乱,但它完成了工作,我头疼了好久才完成它。还请注意,在完整程序中,教授要求我们如果检测到重复值,则抛出异常以获取额外学分。我已经做到了,但我注释掉了它以完成原始任务,请忽略它。