Java, как заменить переменные в методе - PullRequest
0 голосов
/ 26 января 2012

Мне нужно заменить все вхождения именем, данным пользователем, новым именем.Вот мой код:

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 ]

4 голосов
/ 26 января 2012

Для меня это ужасная идея.Вместо этого я предлагаю что-то вроде этого:

// 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 голосов
/ 26 января 2012

Звоните studentInfo.replace(name, studentName) вместо studentInfo.replaceAll(name, studentName).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...