gpt4 book ai didi

java - 让用户创建业务或个人联系人的代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:00 26 4
gpt4 key购买 nike

我有一个 PersonalContact 类和一个 BusinessContact 类设置,我想使用这个驱动程序来提示用户输入联系信息。输入信息后,我想使用这些类来打印它们的 toStrings 以显示联系信息。我认为我需要创建一个新的 PersonalContact 或 BusinessContact 对象,对吗?基类称为 Contact,是一个抽象类。

import java.util.Scanner;

public class PlannerMain {
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {

while (true) {

System.out.println("Create new contact?");
System.out.println("1.Personal contact ");
System.out.println("2.Business Contact ");
System.out.println("3.Exit.");

int option = scanner.nextInt();

if (option == 1) { //Create Personal Contact

System.out.println("Name?");
String name = scanner.next();

System.out.println("Age?");
int age = scanner.nextInt();

System.out.println("Address?");
String address = scanner.next();

System.out.println("City?");
String city = scanner.next();

System.out.println("State?");
String state = scanner.next();

System.out.println("Zip");
String zip = scanner.next();

PersonalContact pc = new PersonalContact;

} // End option 1

else if (option == 2) { // Create Business Contact

System.out.println("Name?");
String name = scanner.next();

System.out.println("Age?");
int age = scanner.nextInt();

System.out.println("Business Phone?");
String businessPhone = scanner.next();

System.out.println("Cellphone?");
String cellPhone = scanner.next();

BusinessContact bc = new BusinessContact;

} // End option 2

else if (option == 3) { /** Terminates the program */
System.exit(0);
} // End option 3
} // End while

}// End void main

}// End

最佳答案

如果你的 person 类是这样的:

public abstract class Contact{
String name;
int age;

public Contact(String name, int age){
this.name = name;
this.age = age;
}
}

那么您的 BusinessContact 可能如下所示

public class BusinessContact extends Contact {
String businessPhone;
String cellPhone;

public BusinessContact(String name, int age, String businessPhone, String cellPhone){
super(name, age);
this.businessPhone = businessPhone;
this.cellPhone = cellPhone;
}

public String toString(){
return "Name: " + this.name + " Age: " + Integer.toString(age) + " Business Phone: " + businessPhone + " Cell Phone: " + cellphone;
}
}

然后你可以替换这一行:

BusinessContact bc = new BusinessContact;

用这个:

BusinessContact bc = new BusinessContact(name, age, businessPhone, cellPhone);

System.out.println(bc.toString());

关于java - 让用户创建业务或个人联系人的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com