Hi there I have this code at the moment as a basic program which just gets a persons name, phone number and account number and then prints it out in the main method.
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();
}
}
However I want to use a constructor like this in my object
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);
}
}
Is it then okay to reuse the same main method with this constructor added or will I need to change my main method.
No, you don't need to change your main method. You can call the parametrized constructor like -
CustomerData p1 = new CustomerData("Mary", "9191919191", "12345");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.