简体   繁体   English

根据 Java 中的布尔值打印特定字符串

[英]Printing a particular String according to boolean value in Java

I m defining a Shape class with constructors, get and set methods, toString methods etc... And in toString method, I have to print " is Filled " or " is not Filled " according to a given boolean value.我正在定义一个带有构造函数、get 和 set 方法、toString 方法等的 Shape 类……在 toString 方法中,我必须根据给定的布尔值打印“已填充”“未填充”

I also wrote a getter method for boolean type such as:我还为布尔类型编写了一个 getter 方法,例如:

    ...
    ...
    private boolean filled;
    ...
    ...

    //Constructor 
    public Shape(boolean f){
        filled = f;
    }
    ...

    // Getter Method for Boolean values
    public boolean isFilled(){
        return filled;
    }

But I have no idea how to write a proper toString method which prints out "is filled " or " is not filled " according to a given value of " boolean filled "但我不知道如何编写一个适当的 toString 方法,该方法根据给定的“布尔值填充”打印出“已填充”“未填充”

any help?有什么帮助吗? thanks in advance提前致谢

You can use the ternary operator to achieve what you want您可以使用三元运算符来实现您想要的

Solution解决方案

boolean filled;
// code
@Override
public String toString(){
    return "blabla " + (filled? "filled" : "not filled") + " other blabla";
}

You can do it like following:你可以这样做:

public String toString()
{
    if(isFilled())
    {
        return "is filled";
    }
    else
    {
        return "is not filled ";
    }
}

How about :怎么样 :

public String toString() {
    return filled ? "is filled" : "is not filled";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM