根据 Java 中的布尔值打印特定字符串
Printing a particular String according to boolean value in Java
我正在用构造函数、get 和 set 方法、toString 方法等定义一个 Shape class...并且在 toString 方法中,我必须打印 " is Filled " 或 " 未填充 " 根据 给定的布尔值。
我还为布尔类型写了一个getter方法如:
...
...
private boolean filled;
...
...
//Constructor
public Shape(boolean f){
filled = f;
}
...
// Getter Method for Boolean values
public boolean isFilled(){
return filled;
}
但我不知道如何编写打印出 "is filled " 或 " 的正确 toString 方法" is not filled "根据给定的值"布尔值填充"
有什么帮助吗?
提前致谢
你可以使用三元运算符来实现你想要的
解决方案
boolean filled;
// code
@Override
public String toString(){
return "blabla " + (filled? "filled" : "not filled") + " other blabla";
}
您可以按照以下方式进行操作:
public String toString()
{
if(isFilled())
{
return "is filled";
}
else
{
return "is not filled ";
}
}
怎么样:
public String toString() {
return filled ? "is filled" : "is not filled";
}
我正在用构造函数、get 和 set 方法、toString 方法等定义一个 Shape class...并且在 toString 方法中,我必须打印 " is Filled " 或 " 未填充 " 根据 给定的布尔值。
我还为布尔类型写了一个getter方法如:
...
...
private boolean filled;
...
...
//Constructor
public Shape(boolean f){
filled = f;
}
...
// Getter Method for Boolean values
public boolean isFilled(){
return filled;
}
但我不知道如何编写打印出 "is filled " 或 " 的正确 toString 方法" is not filled "根据给定的值"布尔值填充"
有什么帮助吗? 提前致谢
你可以使用三元运算符来实现你想要的
解决方案
boolean filled;
// code
@Override
public String toString(){
return "blabla " + (filled? "filled" : "not filled") + " other blabla";
}
您可以按照以下方式进行操作:
public String toString()
{
if(isFilled())
{
return "is filled";
}
else
{
return "is not filled ";
}
}
怎么样:
public String toString() {
return filled ? "is filled" : "is not filled";
}