[英]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
,它是一个数字类型。所以'"' + 999
是1033
,而不是"999
。
要解决此问题,请使用字符串而不是字符:
return "\"" + id() + " - " + date + " - " + text() + "\"";
将toString()
方法从'"'
更改为" \""
。
'"'
是一个字符(在内部存储为整数),因此使用id()
添加它会产生您所看到的结果。
或使用字符串插值:
return '\" ${id()} - ${date} - ${text()} \"';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.