import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
/**
* * 需求:随机生成10个1-100(包含100)之间的不重复随机整数,把其中的奇数并且是3的倍数(可包含3)按从大到小排序(要求不能重复),
* 然后按照指定格式打印到当前工程项目下的num.txt文本中 例如:99, 81, 75, 57, 39, 33, 27, 21, 15, 3
* (注意:最后一个数字没有逗号) 判分标准:完成需求则满分 1:创建一个集合对象 1分 2:创建随机数对象 1分 3,添加符合要求的随机数到集合 2分
* 4,遍历集合并拼接字符串3分 5,使用输出流输出拼接后的字符串,需要try--catch异常并关闭流 3分
* */
public class Day21_1点招题一3 {
public static void main(String[] args) throws IOException {
String str = noDuplicatedRandom();
writerString(str);
}
public static String noDuplicatedRandom() {
Random r = new Random();
int[] arr = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = r.nextInt(100) + 1;
if (arr[0] % 3 != 0) {
i--;
}
for (int j = 0; j < i; j++) {
if (arr[i] % 3 != 0) {
i--;
break;
}
if (arr[j] == arr[i]) {
i--;
break;
}
}
}
bubbleSort(arr);
return printArr(arr);
}
public static void writerString(String str) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter("num.txt");
fw.write(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
fw.close();
}
}
public static int[] bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
public static String printArr(int[] arr) {
String temp = "";
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
temp += Integer.toString(arr[i]);
} else {
temp += Integer.toString(arr[i]) + ",";
}
}
return temp;
}
} |