1. 程式人生 > >JavaSE習題 第七章 常用實用類

JavaSE習題 第七章 常用實用類

問答題

1.怎樣例項化一個Calendar物件?

Calendar ca=Calendar.getInstance();

2.Calendar物件呼叫set(1949,9,1)設定的年月日分別是多少?

就是1949,9,1

3.怎樣得到一個1—100的隨機數?

int a=(int) (Math.random()*100+1);
//或者
Random ra=new Random();
int b=ra.nextInt(100)+1;

4.有集合{1,2,3,4}和集合{1,3,7,9,11}編寫一個應用程式輸出交集並集差集

Set<Integer> s1=new HashSet<>();
        s1.add(
1); s1.add(2); s1.add(3); s1.add(4); Set<Integer> s2=new HashSet<>(); s2.add(1); s2.add(3); s2.add(7); s2.add(9); s2.add(11); s1.retainAll(s2);//交集 System.out.println(s1); s1.addAll(s2);//並集 System.
out.println(s1); s1.removeAll(s2);//差集 System.out.println(s1);

5.硬碟中有2個重要的屬性:價格和容量,編寫一個應用程式,使用TreeMap<K,V>類,分別按照價格和容量排序輸出10個硬碟的資訊

package cn.littlepage.game;

import java.util.TreeMap;

public class test {
    public static void main(String[] args) {
        
        Disk d1
=new Disk(300, 500); Disk d2=new Disk(200, 200); Disk d3=new Disk(800, 300); Disk d4=new Disk(600, 800); Key kp1=new Key(d1.price); Key kp2=new Key(d2.price); Key kp3=new Key(d3.price); Key kp4=new Key(d4.price); Key kc1=new Key(d1.capacity); Key kc2=new Key(d2.capacity); Key kc3=new Key(d3.capacity); Key kc4=new Key(d4.capacity); TreeMap<Key, Disk> diskMap=new TreeMap<>(); diskMap.put(kp1, d1); diskMap.put(kp2, d2); diskMap.put(kp3, d3); diskMap.put(kp4, d4); TreeMap<Key, Disk> diskMap2=new TreeMap<>(); diskMap2.put(kc1, d1); diskMap2.put(kc2, d2); diskMap2.put(kc3, d3); diskMap2.put(kc4, d4); System.out.println(diskMap); System.out.println(diskMap2); } } class Disk{ public int price; public int capacity; public Disk(int price, int capacity) { super(); this.price = price; this.capacity = capacity; } @Override public String toString() { return "Disk [price=" + price + "元, capacity=" + capacity + "GB]\n"; } } class Key implements Comparable{ public int num=0; public Key(int num) { super(); this.num = num; } @Override public int compareTo(Object o) { Key k=(Key)o; return num-k.num; } }
控制檯:{[email protected]=Disk [price=200元, capacity=200GB]
, [email protected]=Disk [price=300元, capacity=500GB]
, [email protected]=Disk [price=600元, capacity=800GB]
, [email protected]=Disk [price=800元, capacity=300GB]
}
{[email protected]=Disk [price=200元, capacity=200GB]
, [email protected]=Disk [price=800元, capacity=300GB]
, [email protected]=Disk [price=300元, capacity=500GB]
, [email protected]=Disk [price=600元, capacity=800GB]
}