2012-01-25 36 views
-1

我需要用新名稱替換用戶給出的名稱。 這裏是我的代碼: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; 
} 

現在它取代的是用戶通過名字的每一個字母。我怎樣才能得到它只替換實際的名字?

+0

的'Student'類不需要第二組變量「studentName」等 - 這可以簡單地使用Person類中的「name」變量,因爲它(Student)是Person的一個子類。 'Student'構造函數可以執行'this.name = studentName',那麼Student甚至不需要重寫'toString',因爲Person.toString已經做了正確的事情。 –

回答

4

對我來說,這是一個可怕的想法。相反,我認爲是這樣的:

// In the student class. 
public String toString() 
{ 
    return "Name: " + studentName + 
     " Address: " + studentAddress + 
     " Email: " + studentEmail + 
     " Phone: " + studentPhone; 
} 

或本

// In the student class. 
public String toString() 
{ 
    return "Name: " + studentName + 
     " Address: " + address + 
     " Email: " + email + 
     " Phone: " + phone; 
} 
+0

我想要它爲個人提供toString()方法 – Josh

+0

,這就是爲什麼我將方法命名爲「toString」的原因。請注意方法名稱上方的註釋; 「在學生課堂」。 – DwB

+0

爲什麼「學生」甚至有_have_「studentName」變量?它可以使用超類的「名稱」。 –

0

撥打studentInfo.replace(name, studentName)而不是studentInfo.replaceAll(name, studentName)

+0

我試過這個,它只是把newName放在第一位。然後它打印所有的studentInfo。 – Josh

+0

這將取代第一次出現的'name',不一定是他想要的那個...... – bdares