Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 495
anon_swe Avatar asked Jun 27 '26 17:06

anon_swe


2 Answers

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;
like image 69
Christian Tapia Avatar answered Jun 30 '26 06:06

Christian Tapia


Your problem is this line:

System.out.println("(" + a + ", " + b + ", " + c + ")");

which is after the while (!answerFound) {...} loop. The compiler thinks that there may be a case where one or more of the variables a, b or c isn't initialised.

Use this line:

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

when declaring the variables, so that they are initialised when declared, and the error should go away.

like image 24
AntonH Avatar answered Jun 30 '26 08:06

AntonH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!