如何在 Java 中将参数与对象进行比较



有人知道如何将参数与对象进行比较吗?我一直在尝试按照最后一个问题中给出的说明进行操作:http://prntscr.com/1zaq0y 但是,似乎并没有引起注意。

public class Classification
    {
        String changes;
        String rating;
        String description;
    Classification()
    {
        rating = "G";
        description = "Suitable for general audiences";
    }
    Classification(String must)
    {
        if(must != "G" || must!= "PG" || must!="M")
        {
            throw new NullPointerException ("Not equal");
        }
        rating = must;
        if(rating == "G")
        {
            description = "Suitable for general audiences";
        }
        if(rating == "PG")
        {
            description = "Parental guidance recommended"; 
        }
        if(rating == "M")
        {
            description = "Suitable for mature audiences";
        }
    }
    Classification (int num, String para)
    {
        if(num!= 13 || num!= 15 || num!=16 || num!=18)
        {
            throw new IllegalArgumentException("Not equal");
        }
        if(para==null)
        {
            throw new NullPointerException("String is null");
        }
        if(num == 16)
        {
            rating = "R";
            description = para;
        }
        changes = rating + num;
    }
    void printClassification()
    {
        print("Rated " + rating + ": " + description);
    }
    void derestrict()
    {
        if(rating == "M")
        {
            rating = "PG";    
        }
        if(rating == "PG")
        {
            rating = "G";
        }
        if(rating == "G")
        {
            throw new IllegalArgumentException("G is least restrictive");
        }
        if(changes == "R18")
        {
            changes = "R16";
        }
        if(changes == "R15")
        {
            changes = "R13";
        }
    }
    Classification isLessRestrictive(Classification compare)
    {
        if(compare==null)
        {
            throw new NullPointerException ("Classification para is null");
        }
        if(changes<compare)
        {
            return true;
        }
        return false;
    }
}

在 Java 中比较 String 时,需要使用 equals()

例如

if(must != "G" || must!= "PG" || must!="M")

应该改为

if(!"G".equals(must) || !"PG".equals(must) || !"M".equals(must))

if(rating == "G")

看起来像这样:

if("G".equals(rating))

相关内容

  • 没有找到相关文章