|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
构造手机类,包含其配置信息:型号(字符串)、内存大小(整数)、存储空间(整数,GB为单位)、价格(整数)。提供带参数的构造函数,重写其equals方法,使得两个相同配置(型号、内存、存储相同即可,价格可不同)的手机为相等的手机。重写其toString函数,打印手机的配置信息,形式为CellPhone [model:xxx, memory:xxx, storage:xxx, price:xxx]
main函数中从键盘读入两个手机对象,比较他们是否相等,输出他们的配置信息。
输入描述:
两个计算机对象,包含型号、内存、存储空间、价格
输出描述:
两个对象是否相等,两个对象的配置信息
输入样例:
在这里给出一组输入。例如:
P20 8 64 4999
P20 8 64 4999
输出样例:
在这里给出相应的输出。例如:
true
CellPhone [model:P20, memory:8, storage:64, price:4999]
CellPhone [model:P20, memory:8, storage:64, price:4999]
下面是我写的代码,重写equals那个有点问题,望指正。
- import java.util.Objects;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- CellPhone c1 = new CellPhone(sc.next(),sc.nextInt(),sc.nextInt(),sc.nextInt());
- CellPhone c2 = new CellPhone(sc.next(),sc.nextInt(),sc.nextInt(),sc.nextInt());
- System.out.println(c1.equals(c2));
- System.out.println(c1);
- System.out.println(c2);
- }
- }
- /* 你的代码将被嵌在这里 */
- class CellPhone{
- String a;
- int b;
- int c;
- int d;
- public CellPhone(String a,int b,int c,int d){
- this.a=a;
- this.b=b;
- this.c=c;
- this.d=d;
- }
- @Override
- public String toString(){
- return "CellPhone [model:"+a+", memory:"+b+", storage:"+c+", price:"+d+"]";
- }
- @Override
- public boolean equals(Object obj){
- CellPhone c=(CellPhone) obj;
- if(this==c) {
- return true;
- }
- return false;
- }
- }
复制代码
重写equals方法时,需要比较两个对象的型号、内存和存储空间是否相同。你的代码中,只是简单地比较了两个对象的引用是否相同,这是不正确的。下面是修改后的代码:
- import java.util.Objects;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- CellPhone c1 = new CellPhone(sc.next(), sc.nextInt(), sc.nextInt(), sc.nextInt());
- CellPhone c2 = new CellPhone(sc.next(), sc.nextInt(), sc.nextInt(), sc.nextInt());
- System.out.println(c1.equals(c2));
- System.out.println(c1);
- System.out.println(c2);
- }
- }
- class CellPhone {
- String model;
- int memory;
- int storage;
- int price;
- public CellPhone(String model, int memory, int storage, int price) {
- this.model = model;
- this.memory = memory;
- this.storage = storage;
- this.price = price;
- }
- @Override
- public String toString() {
- return "CellPhone [model:" + model + ", memory:" + memory + ", storage:" + storage + ", price:" + price + "]";
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null || getClass() != obj.getClass()) {
- return false;
- }
- CellPhone other = (CellPhone) obj;
- return Objects.equals(model, other.model) &&
- memory == other.memory &&
- storage == other.storage;
- }
- }
复制代码
在重写equals方法中,首先判断两个对象的引用是否相同,如果相同则返回true。然后判断传入的对象是否为null或者不是CellPhone类的实例,如果是则返回false。最后比较两个对象的型号、内存和存储空间是否相同,使用Objects.equals方法来比较字符串的相等性,使用==运算符来比较整数的相等性。如果都相等,则返回true,否则返回false。
|
|