我无法从填充了随机整数的数组中删除重复项。我编写了一个 java 类来生成随机数,并在我的主程序中调用了这些随机数,它们将这些随机数写入 .txt 文件。然后我将从这个 .txt 文件中读取数据并将它们存储在一个新数组中,删除所有重复项。接下来,我必须将新的随机数集重新写入一个新的 .txt 文件,其中第一行的数字最小,最后一行的数字最大。所以新列表中的顺序无关紧要。
我的问题是我不确定如何删除重复项。我可以从发布的其他问题中看到人们说要使用 Set 或 hashset 但我已经研究过这些。那么是否有另一种方法可以通过遍历数组或其他方式来删除它们?
import java.io.*;
class MainProg{
public static void main (String[]args){
GenKeys keys = new GenKeys();
//System.out.println(keys.getrandom());
//System.out.println(keys.getrandom());
try{
String f = "keys.txt";
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
for (int i=1; i<=500; i++){
//bw.write(i+ System.getProperty("line.separtor"));
bw.write(keys.getrandom() + "\r\n");
}
// close the file after all the writing has taken place
bw.close ();
} catch (IOException e){
System.out.println ("Error writing to file" + e.toString());
}
// declare a place to store each line as it is read in
String str;
String myArray[] = new String [500];
int i = 0;
try{
FileReader fr = new FileReader("keys.txt");
BufferedReader in = new BufferedReader(fr);
// read in the first line from the file
str = in.readLine();
while(str!=null){
myArray[i] = str;
str = in.readLine();
i++;
}
// close the file
in.close();
}catch(IOException e){
System.out.print(e.toString());
System.out.print("Non-Existant File");
}
int [] mySortedArray = new int [500];
for(int k = 0; k<mySortedArray.length;k++){
for(int j = 0;j<mySortedArray.length;j++){
if(mySortedArray[j] != k){
mySortedArray[k] = j;
System.out.print(mySortedArray[k]);
}
}
}
}
}
}