【发布时间】:2016-04-13 03:47:31
【问题描述】:
在给定特定条件的情况下,有没有办法打印两个不同的覆盖 toString 消息?例如,下面是一个简单的示例,如果检查值为 0,我需要打印两条不同的错误消息。 我已覆盖 toString 以打印“错误:检查 = 0”,但我无法显示“错误:双值不精确”。
public class test{
public static void main(String[] args)
{
System.out.println(new Set(1,0)); // Should print "Error: Check = 0"
System.out.println(new Set(1,0).toDouble()); // Should print "Error: Double value not precise"
}
}
// ------------------------------------------
public class Set{
int a;
int check;
Fraction(int a, int check)
{
this.a = a;
this.check = check;
}
// ------------------------------------------
public String toString()
{
if(this.check == 0)
return "Error: Check = 0";
return (this.a + ":" + this.check);
}
// ------------------------------------------
public double toDouble()
{
double number;
if(this.check != 0)
number = ((a * check) + (1/3));
else
number = 0;
return number;
}
// ------------------------------------------
public String toString(double d)
{
return ("" + d);
}
}
【问题讨论】:
-
为什么不使用自定义异常呢!
-
“错误:双值不精确”的覆盖 toString() 位于何处?
-
你不能这样做,因为你的 tostring 在第二个函数的情况下不会被调用,因为它返回 double
-
我尝试添加一个 String toString(Double d) 方法,但它没有在 println 执行中被调用。 (顺便说一句,反对票是什么?)
标签: java double tostring println