gpt4 book ai didi

java - 未定义大于表达式,java

转载 作者:行者123 更新时间:2023-12-01 10:56:46 25 4
gpt4 key购买 nike

目前正在用java编写代码来玩纸牌游戏“War”。我遇到的一个错误是:

The operator > is undefined for the argument type(s) Class<capture#1-of ? extends Card>, Class<capture#2-of ? extends Card> The operator < is undefined for the argument type(s) Class<capture#3-of ? extends Card>, Class<capture#4-of ? extends
Card>
"

我编写的代码是这样的(与“<”表达式相同)

if (player1Card.getClass() > player2Card.getClass()) {
player1Cards.addLast(player2Card) ;
player1Cards.addLast(player1Card) ;

如何定义小于和大于符号?我不确定将定义放在哪里,Eclipse 仅显示错误消息。

最佳答案

player1Card.getClass() 返回一个 Class 类型的对象。 Java 无法使用 > 运算符来比较类。您无法在 java 中重新定义运算符。

但是,您可以像这样比较类名的长度:

if (player1Card.getClass().getName().length() > player2Card.getClass().getName().length()) {...

或者您可以定义自己的比较方法:

if (greaterThan(player1Card.getClass(), player2Card.getClass()) {...

// and somewhere else in the same .java file:
public boolean greaterThan(Class clazz1, Class clazz2) {...

或者,更复杂的是,为类编写一个Comparator

关于java - 未定义大于表达式,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33587846/

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