Java: 为什么我的 toString 方法打印错误信息?

Java: Why does my toString method print wrong information?

我有一个具有两个属性的抽象超类:int 和 string。我已经覆盖了其中的 toString 方法及其具有一个额外属性 (LocalDate) 的子类。但是,出于某种我不明白的原因,当我打印子类 toSring 信息时,int 值发生了变化。

这是我在超类中的内容:

public abstract class File {
private int id;
private String text;

public File(int newId, String newText) throws IllegalArgumentException {
      id(newId);
      text(newText);
}

public int id() {
   return id;
}

public void id(int e) throws IllegalArgumentException {      
   if (e <= 0) {
      throw new IllegalArgumentException();
   }
   else {
      id = e;
   }
}

public String text() {
   return text;
}

public void text(String aText) throws IllegalArgumentException {
   if (aText == null || aText.length() == 0) {
      throw new IllegalArgumentException();
   }
   else {
      text = aText;
   }
}

@Override
public String toString() {
   return '"' + id() + " - " + text() + '"';
}

然后在子类中我有这个:

public class DatedFile extends File {
private LocalDate date;

public DatedFile (int newId, LocalDate newDate, String newText) throws IllegalArgumentException {
   super(newId, newText);
   date(newDate);
}

public LocalDate date() {
   return date;
}

public void date(LocalDate aDate) throws IllegalArgumentException {
   if (aDate == null) {
      throw new IllegalArgumentException();
   }
   else {
      date = aDate;
   }
}
@Override
public String toString() {
   return '"' + id() + " - " + date + " - " + text() + '"';
}

我是这样测试的:

public static void main(String[] args) {
   LocalDate when = LocalDate.of(2020, 1, 1);
   DatedFile datedFile1 = new DatedFile(999, when, "Insert text here");
   System.out.println(datedFile1);

它打印:“1033 - 2020-01-01 - 在此处插入文本” 但是,如果我使用以下代码

System.out.println(datedFile1.id());

它打印出正确的 ID (999)。所以我假设是 toString 的东西搞砸了,但我不知道问题出在哪里。

PS。我是初学者,如果我包含了太多代码,我很抱歉,但由于我不知道问题出在哪里,我真的不知道什么是相关的,什么不是。

你的问题在这里:

return '"' + id() + " - " + date + " - " + text() + '"';

id()returns是一个int,而'"'是一个char,是数值类型。所以 '"' + 9991033,而不是 "999

要解决此问题,请使用字符串而不是字符:

return "\"" + id() + " - " + date + " - " + text() + "\"";

将您的 toString() 方法从 '"' 更改为 " \""

'"' 是一个字符(在内部存储为整数),因此将其与 id() 相加会产生您所看到的结果。

或使用字符串插值:

return '\" ${id()} - ${date} - ${text()} \"';