我的大多数 Java 程序都在线程“主”java.lang.ArrayOutOfBoundsException 中出现异常:2 错误。我应该如何解决这个问题?

问题描述 投票:0回答:1

我是编程新手。我已经上了一个星期的课了,我的大部分 Java 程序都被这个问题困住了。其中一个代码执行完美并显示所需结果的程序出现异常。但是对于我的其他一些程序,我遇到了同样的错误,

“线程“主”java.lang.ArrayOutOfBoundsException 中的异常:2.

过去几天我一直坚持这个问题,我在网上到处搜索解决方案,但没有一个解决我的问题。

以下是我的代码截图。一个简单的程序,它接受三个 int 命令行参数并确定它们是否构成某个直角三角形的边长。

这是我运行代码时得到的错误:

我的班级进展很快,所以我在其他提交上落后了,所以如果你能帮助我。

我尝试创建一个程序来确定三个 int 值是否属于直角三角形。作业有两个条件;

  1. 每个整数必须为正数
  2. 两个整数的平方和必须等于第三个整数的平方。

我声明并赋值了整数,然后创造了满足赋值条件的条件。我希望得到三个值和布尔值 isRightTriangle 的结果。

java boolean triangle
1个回答
0
投票

你在正确的轨道上尝试以下操作:

class RightAngledTriangle {
    /**
     * Determines if the given integers form a right-angled triangle.
     * The integers must be positive and the sum of the squares of
     * two of the integers must equal the square of the third integer.
     *
     * @param a The first integer.
     * @param b The second integer.
     * @param c The third integer.
     * @return true if the integers form a right-angled triangle, false otherwise.
     */
    public static boolean isRightAngledTriangle(int a, int b, int c) {
        if (a <= 0 || b <= 0 || c <= 0) {
            return false;
        }
        int aSquared = a * a;
        int bSquared = b * b;
        int cSquared = c * c;
        return (aSquared + bSquared == cSquared) ||
               (aSquared + cSquared == bSquared) ||
               (bSquared + cSquared == aSquared);
    }

    public static void main(String[] args) {
        int a = 3;
        int b = 4;
        int c = 5;
        boolean result = isRightAngledTriangle(a, b, c);
        System.out.println("Can integers " + a + ", " + b + ", " + c
                + " form a right-angled triangle? " + result);
    }
}

输出:

Can integers 3, 4, 5 form a right-angled triangle? true
© www.soinside.com 2019 - 2024. All rights reserved.