使用类的方式描述计算机。
提示:计算机的各部件可以作为类的属性,toString()方法用于显示输出计算机相关配置信息。计算机的主要不见包括CPU、主板、显示器、硬盘、内存等。
下面是我写的代码,请帮忙看下对吗?谢谢了。
- Java code
public class Computer { //定义类 //定义属性 String cpu ; //中央处理器 String Motherboard; //主板 String Display; //显示器 String HardDisk; //硬盘 String Memory; //内存 //定义方法 public String toString(){ return "中央处理器:RR4\t"+cpu+"主板:1.7GHZ\t"+Motherboard+"显示器:1024*768\t"+Display+"硬盘:1000G\t"+HardDisk+"内存:10G\t"+Memory; } public static void main(String[] args) { Computer center = new Computer (); //创建对象 System.out.println(center); //使用toString调用 }}
------解决方案--------------------
- Java code
public class Computer { private String cpu ; private String Motherboard; private String Display; private String HardDisk; private String Memory; public Computer() { super(); } public Computer(String cpu, String motherboard, String display, String hardDisk, String memory) { super(); this.cpu = cpu; Motherboard = motherboard; Display = display; HardDisk = hardDisk; Memory = memory; } public String toString(){ return "中央处理器:RR4\t"+cpu+"主板:1.7GHZ\t"+Motherboard+"显示器:1024*768\t"+Display+"硬盘:1000G\t"+HardDisk+"内存:10G\t"+Memory; } public static void main(String[] args) { Computer center = new Computer ("i7","华硕H67","三星","希捷2TB","4G"); System.out.println(center); }}
------解决方案--------------------
- Java code
public class Computer { private String cpu ; private String Motherboard; private String Display; private String HardDisk; private String Memory; public String getCpu(){ return this.cpu ; } public void setCpu(String cpu){ this.cpu = cpu ; } public Computer() { super(); } //其他属性的setter 和getter方法 public Computer(String cpu, String motherboard, String display, String hardDisk, String memory) { super(); this.cpu = cpu; Motherboard = motherboard; Display = display; HardDisk = hardDisk; Memory = memory; } @Override public String toString(){ return "中央处理器:"+cpu+" , 主板:"+Motherboard+" , 显示器:1024*768\t"+Display+ " , 硬盘:1000G\t"+HardDisk+" , 内存:10G\t"+Memory; } public static void main(String[] args) { Computer center = new Computer ("i7","华硕H67","三星","希捷2TB","4G"); System.out.println(center); }}