基本上,我尝试获取一个多达20个整数的数组,并消除数组中可能存在的重复项。我只能用for循环来实现这一点,但我必须用while循环来实现,因为数组中的数字数量可能多达20个,而且我事先不知道。
这是我的密码:
import java.util.Scanner;
import java.io.*;
public class Main
{
public static void main(String[] args) throws FileNotFoundException {
//Gets data from file and assigns variables
Scanner input = new Scanner(new File("in.file"));
int num = 18;
int[] numberList = new int[num];
//Displays that which is in the file
System.out.printf("The original integers are: ");
for (int z = 0; z < numberList.length; z++) {
numberList[z] = input.nextInt();
System.out.printf(numberList[z]+" ");
}
//Activates EliminateDuplicates
EliminateDuplicates(numberList, num);
}
//Method to sift through data and get rid of duplicates
public static int EliminateDuplicates(int[] numberList, int num) {
//Parameter array
int[] newInt = new int[num];
int[] array = new int[numberList.length];
int arrayList = 0;
for (int c = 0; c < numberList.length; c++) {
//If parameter and integer are the same the boolean is true
boolean duplicate = false;
for (int b = 0; b < numberList.length; b++) {
if (array[b] == numberList[c]) {
duplicate = true;
}
}
//Incase duplicate becomes true
if (!duplicate) {
array[arrayList++] = numberList[c];
}
}
//Final array for output
newInt = new int[arrayList];
for (int c = 0; c < arrayList; c++) {
newInt[c] = array[c];
}
//Returns num and activate PrintIntegers
PrintIntegers(newInt);
return num;
}
//Method for the output
public static void PrintIntegers(int[] newInt) {
//Prints the output
System.out.printf("\nThe distinct integers are: ");
for (int x = 0; x < newInt.length; x++) {
System.out.printf(newInt[x]+" ");
}
}
}
它工作,但它只在输入文件有18个整数时工作。
3条答案
按热度按时间hi3rlvi21#
如果您可能不使用set接口(谁为您做肮脏的工作),您可以使用此代码。
lf3rwulv2#
我建议你看看
Set
班级。这是消除重复项的最简单、最优雅的方法。bis0qfac3#
尝试以下操作:
祝你好运!