範例五:電腦選購
分別加入三種不同之cpu,hd,ram
i3,"2TB","8GB"
i5,"4TB","8GB"
i7,"4TB","16GB"
- import java.util.ArrayList;
- public class Ch05 {
- ArrayList<Computer> list=new ArrayList<Computer>();
- Ch05()
- {
- list.add(new Computer("i3","2TB","8GB"));
- list.add(new Computer("i5","4TB","8GB"));
- list.add(new Computer("i7","4TB","16GB"));
- //list.add(new Computer("i5","2TB","16GB"));
- System.out.println("總共選購了"+list.size()+"台電腦");
- System.out.println("價格依序為");
- for(Computer c: list)
- System.out.println(c.getPrice()+"元");
- }
- public static void main(String[] args) {
- new Ch05();
- }
- }
- class Computer
- {
- String cpu, hd, ram;
- int price=0;
- Computer(String c, String h, String r) {
- cpu=c;
- hd=h;
- ram=r;
- }
- int getPrice()
- {
- if(cpu.equals("i3"))
- price+=3000;
- else if(cpu.equals("i5"))
- price+=5000;
- else
- price+=7000;
- if(hd.equals("1TB"))
- price+=1600;
- else if(hd.equals("2TB"))
- price+=3200;
- else
- price+=6400;
- if(ram.equals("4GB"))
- price+=1200;
- else if(ram.equals("8GB"))
- price+=2400;
- else
- price+=4800;
- return price;
- }
- }
複製代碼 |