1:獲取10個1-20之間的隨機數,要求不能重複
public class Homework1 {
public static void main(String[] args) {
//創建TerrSet集合
TreeSet<Integer> ts = new TreeSet<Integer>();
Random r = new Random();
int count = 0;
while(count < 10) {
//產生1——20隨機數
int number = r.nextInt(20) + 1;
if (!ts.contains(number)) {
ts.add(number);
count++;
}
}
//遍歷
for (Integer in : ts) {
System.out.print(in+" ");
}
}
}
2:鍵盤錄入多個數據,以0結束,要求在控制檯輸出這多個數據中的最大值
public static void main(String[] args) {
// 創建鍵盤錄入數據對象
Scanner sc = new Scanner(System.in);
// 鍵盤錄入多個數據,不知道多少個,用集合存儲
ArrayList<Integer> array = new ArrayList<Integer>();
while (true) {
System.out.println("請輸入數據:");
int number = sc.nextInt();
if (number != 0) {
array.add(number);
} else {
break;
}
}
// 把集合轉成數組
// public <T> T[] toArray(T[] a)
Integer[] i = new Integer[array.size()];
array.toArray(i);
// 對數組排序
Arrays.sort(i);
// 獲取該數組中的最大索引的值
System.out.println( "最大值是:" + i[i.length - 1]);
for(Integer in:i) {
System.out.print(in+" ");
}
}
}