gpt4 book ai didi

java - Java中如何比较参数和对象?

转载 作者:行者123 更新时间:2023-12-01 13:57:28 24 4
gpt4 key购买 nike

有人知道如何将参数与对象进行比较吗?我一直在尝试按照此处最后一个问题中给出的说明进行操作: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))

关于java - Java中如何比较参数和对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19554332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com