我创建了一个Java程序,它将用户输入作为整数数组,并打印该数组中的任何重复值及其索引。例如,用户输入5作为数组大小,然后输入5个数字,如1、1、1、1和1。程序应打印:重复编号:1重复编号:1重复编号:1重复数字索引:2重复数字:1重复数字索引:3重复数字:1重复数字索引:4
然而,程序打印:重复号码:一个重复号码的索引:一个重复数字的索引:两个重复数字的索引:三个重复数字的索引:三个重复数字的索引:四个重复数字的索引:一个重复数字的索引:两个重复数字的索引:三个重复编号的索引:一个重复号码的索引:一个重复号码的索引:三个重复号码的索引:四个重复号码的索引:四个重复数字的索引:4重复号码的索引:4重复号码的索引:4重复号码的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:4重复编号的索引:3重复号码的索引:3重复编号的索引:
我试着调试程序,得出的结论是,由于打印结果在循环中,只要循环运行并满足一定条件,就会有多个打印。但是,我无法找到使代码不同的方法,因此只打印出正确的结果数。我试着调整代码:插入、中断和继续,将print.out语句放在循环之外,但是没有工作。
Scanner sc = new Scanner(System.in); int i, j;
System.out.println("This program lets you enter an array of numbers, and then tells you if any of the numbers are duplices, and what the duplicates' indices are. \nPlease enter your desired array size: ");
int arraySize = sc.nextInt();
while (arraySize <= 0) { System.out.println(arraySize + " is not a valid number. \nPlease enter your desired array size: ");
arraySize = sc.nextInt(); continue;}
int[] arrayList = new int[arraySize];
System.out.println("Please enter your array values: ");
for (i = 0; i < arraySize; i++) {
arrayList[i] = sc.nextInt(); }
for (i = 0; i < arrayList.length; i++) {
for (j = i + 1; j < arrayList.length; j++) {
if (i!=j && arrayList[i] == arrayList[j]) {
System.out.println("Duplicate number: " + arrayList[i]);
System.out.println("Duplicate number's index: " + j); }
else if (i!=j && arrayList[i] != arrayList[j]) {System.out.println("There are no duplicates"); }
}
}发布于 2019-07-27 02:02:08
你正在做的是找到一个重复的副本。取1, 1,1。首先你发现两个重复的1,0在索引1和2。然后你发现一个重复的1,索引1在索引2。有几个解决方案。
list来存放找到的副本,并使用contains方法来检查它是否存在。你也有不同的问题。
boolean标志,如果找到重复项,则设置为false,并在退出循环时使用该标记打印消息。j = 0 and i = j+1)多一个,所以它们永远不会相同。所以你不需要(i!=j)测试。另外,外部循环的终止应该是arrayList.length-1。https://stackoverflow.com/questions/57228565
复制相似问题