【发布时间】:2016-03-30 08:52:52
【问题描述】:
我正在编写一个程序,该程序旨在读取一个充满链接的 .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]);
}
}
}
编辑:我当前的未排序算法正在按起始顺序显示所有链接。
【问题讨论】:
-
你知道
List,比如ArrayList吗? -
@Maljam 我听说过,但我不熟悉。这会让这项工作更容易吗?
-
是的,您对涉及
ArrayList的解决方案还满意吗? -
@Maljam 当然,那样我会学到一些新东西:D
-
仅供参考 - 有一个标准的洗牌算法,称为 Fisher-Yates 或 Knuth Shuffle:algs4.cs.princeton.edu/11model/Knuth.java.html 或 dotnetperls.com/shuffle-java
标签: java arrays algorithm sorting