听起来有点愚蠢,但我需要toString()
方法的帮助,这非常令人讨厌。
我尝试在网上查找,因为toString
是它正在搞砸了“并没有找到Kid构造函数#2”,即使它在那里,我甚至会做其他事情并且它不起作用。
好的,这就是我的代码:
import java.util.*;
class Kid {
String name;
double height;
GregorianCalendar bDay;
public Kid () {
this.name = "HEAD";
this.height = 1;
this.bDay = new GregorianCalendar(1111,1,1);
}
public Kid (String n, double h, String date) {
// method that toString() can't find somehow
StringTokenizer st = new StringTokenizer(date, "/", true);
n = this.name;
h = this.height;
}
public String toString() {
return Kid(this.name, this.height, this.bDay);
}
} //end class
好的,所以上面的toString(我知道,我的第三个参数是关闭的,应该是一个String)是关闭的。如果我硬编码第三件事的价值它会变得混乱,并说它找不到这个(上面)。那么我怎样才能得到日期并将其分解?
调用此类的课程在
之下class Driver {
public static void main (String[] args) {
Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");
System.out.println(kid1.toString());
} //end main method
} //end class
我尝试过研究多个构造函数,但实际上并没有帮助。
我尝试研究toString()
方法,并尝试使用我之前创建的以前的toString()
方法逻辑,但这是全新的,因此它从未起作用。
帮助?
答案 0 :(得分:119)
toString
应该返回String
。
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
我建议您使用IDE的功能来生成toString
方法。不要手工编码。
例如,如果只需右键单击源代码并选择Source > Generate toString
答案 1 :(得分:9)
Java toString()方法
如果要将任何对象表示为字符串,则toString()方法就会出现。
toString()方法返回对象的字符串表示形式。
如果打印任何对象,java编译器会在内部调用对象上的toString()方法。所以重写toString()方法,返回所需的输出,它可以是对象的状态等取决于你的实现。
Java toString()方法的优点
通过重写Object类的toString()方法,我们可以返回对象的值,因此我们不需要编写太多代码。
没有toString()方法的输出
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student@2kaa9dc
Student@4bbc148
您可以在上面的示例#1中看到。打印s1和s2打印对象的Hashcode值,但我想打印这些对象的值。由于java编译器内部调用toString()方法,因此重写此方法将返回指定的值。让我们通过下面给出的例子来理解它:
Example#2
Output with overriding toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
//overriding the toString() method
public String toString(){
return id+" "+name+" "+address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:100 Joe success
50 Jeff fail
请注意,toString()主要与Java中的多态性概念有关。 在Eclipse中,尝试单击toString()并右键单击它。然后,单击Open Declaration并查看Superclass toString()的来源。
答案 2 :(得分:4)
您可以在toString()中创建新对象。 使用
return "Name = " + this.name +" height= " + this.height;
而不是
return Kid(this.name, this.height, this.bDay);
您可以根据需要更改返回字符串。还有其他方法来存储日期而不是calander。
答案 3 :(得分:3)
您无法将构造函数称为普通方法,只能使用new
调用它来创建新对象:
Kid newKid = new Kid(this.name, this.height, this.bDay);
但是从你的toString()方法构造一个新对象并不是你想要做的。
答案 4 :(得分:2)
以下代码是一个示例。基于相同的问题而不是使用基于IDE的转换,是否有更快的实现方式,以便将来发生更改时,我们不需要反复修改值?
@Override
public String toString() {
return "ContractDTO{" +
"contractId='" + contractId + '\'' +
", contractTemplateId='" + contractTemplateId + '\'' +
'}';
}
答案 5 :(得分:1)
实际上你需要返回这样的东西,因为toString必须返回一个字符串
public String toString() {
return "Name :" + this.name + "whatever :" + this.whatever + "";
}
你实际上在构造函数中做了一些错误,你将用户设置的变量设置为名称,而你需要做相反的事情。 你应该做什么
n = this.name
你应该做什么
this.name = n
希望这有助于谢谢
答案 6 :(得分:1)
我们甚至可以这样编写,方法是在类中创建一个新的String对象,并在构造函数中为它指定我们想要的东西,并在被覆盖的toString方法中返回
public class Student{
int id;
String name;
String address;
String details;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
this.details=id+" "+name+" "+address;
}
//overriding the toString() method
public String toString(){
return details;
}
public static void main(String args[]){
Student s1=new Student(100,"Joe","success");
Student s2=new Student(50,"Jeff","fail");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
答案 7 :(得分:1)
如果您对单元测试感兴趣,则可以声明一个公共的“ ToStringTemplate”,然后可以对toString进行单元测试。即使您不对其进行单元测试,我也认为它“更干净”并使用String.format。
extensions [ view2.5d ]
globals [ max-sheep ] ; don't let sheep population grow too large
; Sheep and wolves are both breeds of turtle.
breed [ sheep a-sheep ] ; sheep is its own plural, so we use "a-sheep" as the singular.
breed [ wolves wolf ]
turtles-own [ energy ] ; both wolves and sheep have energy
patches-own [ countdown ]
to setup
clear-all
ifelse netlogo-web? [set max-sheep 10000] [set max-sheep 30000]
; Check model-version switch
; if we're not modeling grass, then the sheep don't need to eat to survive
; otherwise the grass's state of growth and growing logic need to be set up
ifelse model-version = "sheep-wolves-grass" [
ask patches [
set pcolor one-of [ green brown ]
ifelse pcolor = green
[ set countdown grass-regrowth-time ]
[ set countdown random grass-regrowth-time ] ; initialize grass regrowth clocks randomly for brown patches
]
]
[
ask patches [ set pcolor green ]
]
create-sheep initial-number-sheep ; create the sheep, then initialize their variables
[
set shape "sheep"
set color white
set size 1.5 ; easier to see
set label-color blue - 2
set energy random (2 * sheep-gain-from-food)
setxy random-xcor random-ycor
]
create-wolves initial-number-wolves ; create the wolves, then initialize their variables
[
set shape "wolf"
set color black
set size 2 ; easier to see
set energy random (2 * wolf-gain-from-food)
setxy random-xcor random-ycor
]
display-labels
reset-ticks
view2.5d:turtle-view "wsp" turtles [ t -> [energy] of t ]
end
to go
; stop the simulation of no wolves or sheep
if not any? turtles [ stop ]
; stop the model if there are no wolves and the number of sheep gets very large
if not any? wolves and count sheep > max-sheep [ user-message "The sheep have inherited the earth" stop ]
ask sheep [
move
if model-version = "sheep-wolves-grass" [ ; in this version, sheep eat grass, grass grows and it costs sheep energy to move
set energy energy - 1 ; deduct energy for sheep only if running sheep-wolf-grass model version
eat-grass ; sheep eat grass only if running sheep-wolf-grass model version
death ; sheep die from starvation only if running sheep-wolf-grass model version
]
reproduce-sheep ; sheep reproduce at random rate governed by slider
]
ask wolves [
move
set energy energy - 1 ; wolves lose energy as they move
eat-sheep ; wolves eat a sheep on their patch
death ; wolves die if our of energy
reproduce-wolves ; wolves reproduce at random rate governed by slider
]
if model-version = "sheep-wolves-grass" [ ask patches [ grow-grass ] ]
; set grass count patches with [pcolor = green]
tick
display-labels
view2.5d:update-turtle-view "wsp" turtles
end
to move ; turtle procedure
rt random 50
lt random 50
fd 1
end
to eat-grass ; sheep procedure
; sheep eat grass, turn the patch brown
if pcolor = green [
set pcolor brown
set energy energy + sheep-gain-from-food ; sheep gain energy by eating
]
end
to reproduce-sheep ; sheep procedure
if random-float 100 < sheep-reproduce [ ; throw "dice" to see if you will reproduce
set energy (energy / 2) ; divide energy between parent and offspring
hatch 1 [ rt random-float 360 fd 1 ] ; hatch an offspring and move it forward 1 step
]
end
to reproduce-wolves ; wolf procedure
if random-float 100 < wolf-reproduce [ ; throw "dice" to see if you will reproduce
set energy (energy / 2) ; divide energy between parent and offspring
hatch 1 [ rt random-float 360 fd 1 ] ; hatch an offspring and move it forward 1 step
]
end
to eat-sheep ; wolf procedure
let prey one-of sheep-here ; grab a random sheep
if prey != nobody [ ; did we get one? if so,
ask prey [ die ] ; kill it, and...
set energy energy + wolf-gain-from-food ; get energy from eating
]
end
to death ; turtle procedure (i.e. both wolf nd sheep procedure)
; when energy dips below zero, die
if energy < 0 [ die ]
end
to grow-grass ; patch procedure
; countdown on brown patches: if reach 0, grow some grass
if pcolor = brown [
ifelse countdown <= 0
[ set pcolor green
set countdown grass-regrowth-time ]
[ set countdown countdown - 1 ]
]
end
to-report grass
ifelse model-version = "sheep-wolves-grass" [
report patches with [pcolor = green]
]
[ report 0 ]
end
to display-labels
ask turtles [ set label "" ]
if show-energy? [
ask wolves [ set label round energy ]
if model-version = "sheep-wolves-grass" [ ask sheep [ set label round energy ] ]
]
end
; Copyright 1997 Uri Wilensky.
; See Info tab for full copyright and license.
现在,您可以通过创建Kid,设置属性并在ToStringTemplate上进行自己的string.format并进行比较来进行单元测试。
使ToStringTemplate静态最终意味着真相的“一个版本”,而不是在单元测试中拥有模板的“副本”。
答案 8 :(得分:1)
答案 9 :(得分:0)
正如其他人解释的那样,persist()
并不是实例化您的课程的地方。相反,toString
方法旨在构建一个表示您的类的实例的值的字符串,至少报告存储在该对象中的数据的最重要字段。在大多数情况下,toString
用于调试和日志记录,而不用于您的业务逻辑。
toString
从Java 8和更高版本开始,实现StringJoiner
的最现代方法将使用StringJoiner
类。
类似这样的东西:
toString
Person [name = Alice | phone = 555.867.5309]
答案 10 :(得分:0)
我认为最好的方法是使用Google gson库:
@Override
public String toString() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
或apache commons lang反射方式
答案 11 :(得分:0)
如果您使用记事本: 然后
public String toString(){
return ""; ---now here you can use variables which you have created for your class
}
如果您使用的是Eclipse IDE,则 按
-alt +shift +s
-单击覆盖toString方法,在这里您将获得选择要选择的变量类型的选项。
答案 12 :(得分:0)
简洁明了的方法是使用Lombok批注。它具有@ToString
批注,它将生成toString()
方法的实现。默认情况下,它将按顺序打印您的班级名称以及每个字段,并以逗号分隔。
您可以通过将参数传递给注释来轻松自定义输出,例如:
@ToString(of = {"name", "lastName"})
相当于纯Java:
public String toString() {
return "Person(name=" + this.name + ", lastName=" + this.experienceInYears + ")";
}
答案 13 :(得分:0)
如果仅使用toString()
来调试DTO,则可以使用以下内容自动生成可读的输出:
import com.fasterxml.jackson.databind.ObjectMapper;
...
public String toString() {
try { return new ObjectMapper().writeValueAsString(this); }
catch (Exception e) { return "{ObjectMapper failed}"; }
}
但是,如果DTO可能包含PII(不应在日志中捕获),则这不适用于生产部署。