我需要用新名稱替換用戶給出的名稱。 這裏是我的代碼:java如何替換方法中的變量
public class Person
{
public Person() {}
public Person(String name, String address, String email, String phone)
{
this.name = name;
this.address = address;
this.email = email;
this.phone = phone;
}
String name = "";
String address = "";
String email = "";
String phone = "";
public String toString()
{
return "Name: " + name + " Address: " + address + " Email: " + email + " Phone: " + phone;
}
}
class Student extends Person
{
public Student() {}
public Student(String studentName, String studentAddress, String studentEmail, String studentPhone)
{
this.studentName = studentName;
this.studentAddress = studentAddress;
this.studentEmail = studentEmail;
this.studentPhone = studentPhone;
}
public String toString()
{
String studentInfo = super.toString();
return studentInfo.replaceAll(name, studentName);
}
//int grade = 0; COME BACK TO THIS
String studentName = "";
String studentAddress = "";
String studentEmail = "";
String studentPhone = "";
public static final int freshman = 0;
public static final int sophomore = 1;
public static final int junior = 2;
public static final int senior = 3;
}
現在它取代的是用戶通過名字的每一個字母。我怎樣才能得到它只替換實際的名字?
的'Student'類不需要第二組變量「studentName」等 - 這可以簡單地使用Person類中的「name」變量,因爲它(Student)是Person的一個子類。 'Student'構造函數可以執行'this.name = studentName',那麼Student甚至不需要重寫'toString',因爲Person.toString已經做了正確的事情。 –