【发布时间】:2015-06-24 17:08:01
【问题描述】:
无法正常工作,它应该对用户输入的任意数量的数字进行排序,然后消除重复项。现在程序只打印 0,但它应该打印一个没有重复的数组。我也必须这样做,我不能使用 Java 的内置排序或数组复制方法。 为什么我的代码只打印 0,我该如何解决?
package Lab_10;
import java.util.Scanner;
public class Eliminating_duplicates
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of numbers: ");
int numOfNums = input.nextInt();
int[] list = new int[numOfNums];
int[] newList = new int[numOfNums];
for( int x = 0; x < list.length; ++x)
{
while(numOfNums != -1 && x < list.length)
{
System.out.print("Enter value " + (x + 1) + ": ");
int value = input.nextInt();
list[x] = value;
++x;
}
}
sortList(list);
System.out.println("Here is the sorted list: ");
for (int x = 0; x < list.length; ++x)
{
System.out.println(list[x]);
}
eliminateDuplicates(list);
System.out.println("Here is the list without duplicates: ");
for (int x = 0; x < newList.length; ++x)
{
System.out.println(newList[x]);
}
}
public static void sortList(int[] list)
{
int temp;
boolean madeASwap = true;
int lastIndex = list.length-1;
while (madeASwap)
{
madeASwap = false;
for (int x = 0; x < lastIndex; ++x)
{
if (list[x] > list[x + 1])
{
temp = list[x];
list[x] = list[x + 1];
list[x + 1] = temp;
madeASwap = true;
}
}
}
}
public static int[] eliminateDuplicates(int[] list)
{
int end = list.length;
for (int i = 0; i < end; i++)
{
for (int j = i + 1; j < end; j++) {
if (list[i] == list[j]) {
for (int k = j + 1; k < end; k++, j++) {
list[j] = list[k];
}
--end;
--j;
}
}
}
int[] newList = new int[end];
return newList;
}
}
【问题讨论】:
-
附带说明:您应该调试代码以真正了解它在做什么。例如:在
main中,嵌套循环有一些冗余。for ( int x = 0; x < list.length; ++x)只会执行一次,因为嵌套的while(numOfNums != -1 && x < list.length) { ... ++x; }将处理所有迭代。