Java 变量可能尚未初始化

2022-01-19 00:00:00 initialization java

我正在从事 Project Euler 问题 9,其中指出:

I'm working on Project Euler Problem 9, which states:

毕达哥拉斯三元组是三个自然数的集合,一个 <b<c,为此,

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^2 + b^2 = c^2

例如,3^2 + 4^2 = 9 + 16 = 25 = 52.

For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.

恰好存在一个毕达哥拉斯三元组,其 a + b + c = 1000.找到产品 abc.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

这是我到目前为止所做的:

Here's what I've done so far:

class Project_euler9 {

    public static boolean determineIfPythagoreanTriple(int a, int b, int c) {
        return (a * a + b * b == c * c);
    }   

    public static void main(String[] args) {
        boolean answerFound = false;
        int a, b, c;
        while (!answerFound) {
            for (a = 1; a <= 1000; a++) {
                for (b = a + 1; b <= 1000; b++) {
                    c = 1000 - a - b;
                    answerFound = determineIfPythagoreanTriple(a, b, c);
                }
            }
        }
        System.out.println("(" + a + ", " + b + ", " + c + ")");
    }
}

当我运行我的代码时,我得到了这个错误:

When I run my code, I get this error:

Project_euler9.java:32: error: variable a might not have been initialized
        System.out.println("The Pythagorean triplet we're looking for is (" + a + ", " + b + ", " + c + ")");

注意:我为每个变量(a、b 和 c)都得到了这个,只是行号不同.

Note: I get this for each of my variables (a, b, and c) just with different line numbers.

我认为当我将 a、b 和 c 声明为整数时,如果未赋值,则默认值为 0.

I thought that when I declared a, b, and c as integers, the default value was 0 if left unassigned.

即使不是这样,在我看来他们都确实被分配了,所以我对这个错误有点困惑.

Even if this weren't the case, it looks to me like they all do get assigned, so I'm a bit confused about the error.

为什么会这样?

推荐答案

实例变量(在您的情况下,它们是 整数)默认分配给 0.局部变量不是.(来自 Java 文档)

Instance variables (in your case, they would be integers) are assigned to 0 be default. Local variables not. (From Java Docs)

如果没有进入循环,那么你的变量将不会被初始化,这就是错误的原因.

If the loop is not entered, then your variables won't be initialized, that's the reason of the error.

你可以做的是在声明时初始化它们:

int a=0, b=0, c=0;

相关文章