随机产生10个整数,然后将这10个整数按从小到大的顺序输出到控制台
程序员文章站
2022-04-04 09:49:24
...
具体要求看图片
不多做解释,代码很简单,仔细看就能懂
package Demo3;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import lombok.ToString;
public class RandDemo {
//创建10个随机数
public static void main(String[] args) throws Exception {
int arr[] = new int[10];
for (int j = 0; j < arr.length; j++) {
int rand = new Random().nextInt(100) + 1;
arr[j] = rand;
}
String str = toString(arr);
System.out.println(str);
outarr(str);
reader();
}
//读取文件并且进行排序然后输出
public static void reader() throws Exception {
File file1 = new File("C:\\Users\\Administrator\\Desktop\\456.txt");
BufferedReader br = new BufferedReader(new FileReader(file1));
String str = null;
String str2 = null;
while ((str = br.readLine()) != null) {
str2 = str;
}
br.close();
String[] arr = str2.split(",");
List<Integer> list = new ArrayList<Integer>();
for (String string : arr) {
if (string != null && !"".equals(string)) {
list.add(Integer.parseInt(string));
}
}
Collections.sort(list);
System.out.println(list);
}
//将字符串写入到文件
public static void outarr(String str) throws Exception {
File file = new File("C:\\Users\\Administrator\\Desktop\\456.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(str);
bw.flush();
bw.newLine();
bw.close();
}
//将数组转换为字符串
public static String toString(int[] arr) {
// 1.定义个临时容器
String temp = "";
// 2.遍历数组,字符串自加
for (int x = 0; x < arr.length; ++x) {
temp += arr[x] + ",";
}
if (temp.length() > 0) {
temp = temp.substring(0, temp.length() - 1);
}
return temp + "";
}
}