簡體   English   中英

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()返回一個int ,而'"'是一個char ,它是一個數字類型。所以'"' + 9991033 ,而不是"999

要解決此問題,請使用字符串而不是字符:

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

toString()方法從'"'更改為" \""

'"'是一個字符(在內部存儲為整數),因此使用id()添加它會產生您所看到的結果。

或使用字符串插值

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM