java如何在方法中替换变量

时间:2012-01-25 21:31:34

标签: java string replace

我需要使用新名称替换所有出现的名称。 这是我的代码:

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;
}

现在它用用户传递的名称替换每个字母。我怎样才能让它只替换实际名称?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

致电studentInfo.replace(name, studentName)而不是studentInfo.replaceAll(name, studentName)

相关问题