您的位置:首页 > 其它

从文本文件中读取随机数,并打印出数字所出现的次数,按次数降序排列

2014-03-21 17:18 357 查看
要求:从txt文件中读取1~1000的1000个随机数,然后记录每一个随机数出现的次数,并且按照随机数出现的次数进行降序排列,最后打印出每一个随机数所出现的次数。

import java.io.*;

public class AlgorithmTest{

public static void main(String[] args)throws Exception{

int a[]=new int[1000];

//文件绝对路径改成你自己的文件路径

FileReader fr=new FileReader("D:\\data.txt");

//可以换成工程目录下的其他文本文件

BufferedReader br=new BufferedReader(fr);

String s = null;

System.out.println("你输入的文本如下:");

try{

do{

s=br.readLine(); //一次读取一行数字

if(s!=null)

{

System.out.println(s);

}

String arrays[] = s.split("\\s+"); //每一个数字按空格隔开

int Length = arrays.length;

int arrayi[] = new int [Length];

for(int i=0;i<Length;i++)

{

arrayi[i] = Integer.parseInt(arrays[i]);

a[arrayi[i]]++; //a数组的元素下标记录随机数,元素值记录随机数所出现的次数

}

}while(s!=null);

br.close();

}catch(Exception e){

e.printStackTrace();

}

int[] b = new int[1000];
//新建一个数组b来记录排序前数组a的下标值(即是出现的随机数值)

for(int i=0; i < 1000; i++) {

b[i] = i;

}

descSort(a, b);

for(int i=0; i<a.length; i++){

System.out.println("数字"+b[i]+"出现的次数为:" + a[i]);

}

}

//改进后的冒泡算法,在降序排列数组a的同时,只要a中元素交换,那么b中元素对应同时交换,这就使得a数组 //降序排列后,b数组中与之对应的元素还是排序之前a数组元素的下标值

public static void descSort(int[] a, int[] b) {

int temp = 0;

for (int i = 0; i < a.length; i++) {

for (int j = 0; j < a.length - 1 - i; j++) {

if (a[j] < a[j + 1]) {

temp = a[j];

a[j] = a[j + 1];

a[j + 1] = temp;

temp = b[j];

b[j] = b[j + 1];

b[j + 1] = temp;

}

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐