您好,我现在有此代码,这是一个基本程序,它只获取人员姓名,电话号码和帐号,然后以main方法将其打印出来。
import java.util.Scanner;
public class CustomerData {
String name;
String phoneNumber;
String accountCode;
String setname() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers name ?");
String name = scanner.nextLine();
return name;
}
String setNumber() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers Phone Number ?");
String phone = scanner.nextLine();
return phone;
}
String setAccountCode() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers account code ?");
String account = scanner.nextLine();
scanner.close();
return account;
}
public void getInfo() {
System.out.println("\nCustomer Name: "+this.name);
System.out.println("Customer Phone Number: "+this.phoneNumber);
System.out.println("Customer Account Code: "+this.accountCode);
}
}
public class BankAccountTest {
public static void main(String args[]) {
CustomerData p1 = new CustomerData();
p1.name = p1.setname();
p1.phoneNumber = p1.setNumber();
p1.accountCode = p1.setAccountCode();
p1.getInfo();
}
}
但是我想在对象中使用这样的构造函数
import java.util.Scanner;
public class CustomerData {
String name;
String phoneNumber;
String accountCode;
CustomerData(String name, String phoneNumber, String accountCode){
this.name = name;
this.phoneNumber = phoneNumber;
this.accountCode = accountCode;
}
CustomerData(){
this.name = "Unknown";
this.phoneNumber = "Unknown";
this.accountCode = "No Registered Account Code";
}
String setname() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers name ?");
String name = scanner.nextLine();
return name;
}
String setNumber() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers Phone Number ?");
String phone = scanner.nextLine();
return phone;
}
String setAccountCode() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers account code ?");
String account = scanner.nextLine();
scanner.close();
return account;
}
public void getInfo() {
System.out.println("\nCustomer Name: "+this.name);
System.out.println("Customer Phone Number: "+this.phoneNumber);
System.out.println("Customer Account Code: "+this.accountCode);
}
}
然后可以在添加此构造函数的情况下重用相同的main方法,还是我需要更改main方法。
答案 0 :(得分:0)
否,您不需要更改主要方法。您可以像-
那样调用参数化的构造函数 CustomerData p1 = new CustomerData("Mary", "9191919191", "12345");