如何使用tostring方法打印两个私有字符串变量 [英] How do I use a tostring method to print two private string variables
本文介绍了如何使用tostring方法打印两个私有字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用toString方法打印出两个String变量,而我尝试过它将无法打印出来并且不会编译。
我尝试过:
i need to print out two String variables using the toString method, and what ive tried it won't print out right and it wont compile.
What I have tried:
public String toString(){
this.dayOfTheWeek = day;
this.name = n;
String day = new String("The name of the show is: " + n + "and airs on: " + day);
System.out.println(day.toString());
推荐答案
我害怕这都错了。变量day
和n
在toString
中不存在方法。它们应该在构造函数中设置:
This is all wrong I'm afraid. The variablesday
andn
do not exist in thetoString
method. They should be set either in the constructor:
class ThisClass {
private int dayOfTheWeek;
private String name;
ThisClass(int day, String name) {
this.dayOfTheWeek = day;
this.name = name;
}
或使用setter(参见添加Setter和Getter方法 - Java EE 6教程 [ ^ ])。
此外,您不应该在 toString中打印数据
方法。其目的是返回一个可由调用者打印的字符串。所以你的方法应该是这样的:
or by using setters (see Adding Setter and Getter Methods - The Java EE 6 Tutorial[^]).
Also you should not be printing the data in the toString
method. Its purpose is to return a string which may be printed by the caller. So Your method should look like:
public String toString(){
String textday = new String("The name of the show is: " + n + "and airs on: " + day);
return textday;
}
这篇关于如何使用tostring方法打印两个私有字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文