Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

initialization - Java variable may not have been initialized

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

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

a^2 + b^2 = c^2

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

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 + ")");

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

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.

Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

What you can do is initialize them when declaring:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...