Java 返回一个 boolean 错误

标签 java methods boolean return collision

我是 java 语言的新手,我很困惑为什么会在这里出错。 这是一段非常短的代码,我似乎对此有心理障碍。 有什么建议吗?

public class Rigidbody {
    public boolean checkCircleCollision(float x1,float y1,float size1,float x2,float y2,float size2){
        if(Math.sqrt(((x2-x1)^2)+((y2-y1)^2))<=(size1+size2)){
            return true;
        }
    }
}

有谁知道我在这里缺少什么? (这可能真的很明显)。

最佳答案

嗯,首先,you forgot to have an else clause :

public boolean checkCircleCollision(float x1, float y1, float r1,
    float x2, float y2, float r2) {
  if (Math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2)) <= (r1 + r2)){
    return true;
  } else {
    return false;
  }
}

Someone else already pointed out这可以缩短如下:

public boolean checkCircleCollision(float x1, float y1, float r1,
    float x2, float y2, float r2) {
  return Math.sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2)) <= (r1 + r2);
}

(确保为他们点赞 :-)


但是,您的代码仍然是错误的。

如前所述here , Java 的 ^ 运算符用于按位异或,而不是取幂。也许你想要 Math.pow()

Returns the value of the first argument raised to the power of the second argument.

public boolean checkCircleCollision(float x1, float y1, float r1,
    float x2, float y2, float r2) {
  return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) <= (r1 + r2);
}

或者,您也可以只使用 Math.hypot而不是自己滚动!

Returns sqrt(x^2 + y^2) without intermediate overflow or underflow.

public boolean checkCircleCollision(float x1, float y1, float r1,
    float x2, float y2, float r2) {
  return Math.hypot(x2 - x1, y2 - y1) <= (r1 + r2);
}

关于Java 返回一个 boolean 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083775/

相关文章:

java - 在java中将 boolean 对象转换为字符串的最佳方法

java - 如何编写一个方法来读取数组列表中的特定内容并计算数组内容的数量

java - 代号 One Timer 问题

java - Java String.getBytes ("UTF-8") 是否保留词典顺序?

java - Eclipse 中 Java 的定制内容辅助

java - 覆盖与隐藏 Java - 困惑

java - ImageView 可以是全局变量吗?

c - 在 C 中使用 char 作为 bool 是不好的做法吗?

java - 使用 3 个 boolean 值的 If 语句

java - 在 map reduce spark 的设置键值对中插入一个 if 循环