我正在编写一个程序,目的是读取一个充满链接的.txt,并对数组中的链接进行解序,以便以后可以随机访问这些链接。
下面是我所做的(它不起作用:D):
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Scan{
public static void main(String[] args) throws FileNotFoundException{
String test = "";
int i = 0;
int temp = 0;
Scanner link = new Scanner(new File("links.txt"));
while(link.hasNextLine()){
test = link.nextLine();
temp++;
}
link.close();
String[] links = new String[temp];
Scanner urls = new Scanner(new File("links.txt"));
for (i = 0; i < temp; i++)
{
test = urls.nextLine();
links[i] = test;
System.out.println("Sorted: " + links[i]);
}
urls.close();
System.out.println("Size of LINKS: " + temp);
// - - - - - - - - - - - - - - - - - - - - - //
// Start of the unsorting algorithm //
// (It's just not working, need a new one) //
// - - - - - - - - - - - - - - - - - - - - - //
String[] copy = new String [temp];
int[] used = new int [temp];
for(i = 0; i < temp; i++)
{
for (int k = 0; k < temp; k++)
{
int j = (int) (Math.random() * temp);
//System.out.println(j);
if (j == used[k])
{
k--;
}
else
{
used[k] = j;
copy[j] = links[i];
}
}
System.out.println(links[i]);
}
}
}编辑:我当前的取消排序算法是按照链接的起始顺序显示所有链接。
发布于 2016-03-30 16:56:59
问题出在第二个循环中,您正在选择一个随机索引j,但是您正在检查是否为used[k] == j,而您应该检查Does the array used contain j?
因此,一种解决方案是创建一个boolean contains(int[] arr, int val)方法来检查它是否已经存在。或者另一个简单的解决方案:
ArrayList<String> links = //read from file
ArrayList<String> unsorted = new ArrayList<String>();
while(links.size() != 0) {
unsorted.add( links.remove( (int)(Math.random()*links.size()) ) );
}如果需要String[]格式的输出,则可以使用unsorted.toArray()
发布于 2017-07-16 16:28:46
你为什么要重新发明轮子?
List<String> list = Arrays.asList(links);
Collections.shuffle(list);
String[] copy = list.toArray(new String[temp]);如果您使用List而不是数组,您的代码会简单得多。
https://stackoverflow.com/questions/36303992
复制相似问题