Java变量可能尚未初始化 [英] Java variable may not have been initialized

查看:81
本文介绍了Java变量可能尚未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Euler项目问题9 ,其中指出:

毕达哥拉斯三联体是一组三个自然数,一个<b<c,为此,

  a ^ 2 + b ^ 2 = c ^ 2 

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

确切存在一个毕达哥拉斯三联体,其中a + b + c = 1000.找到产品abc.

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

  class Project_euler9 {公共静态布尔值defineIfPythagoreanTriple(int a,int b,int c){return(a * a + b * b == c * c);}公共静态void main(String [] args){boolean answerFound = false;int a,b,c;同时(!answerFound){对于(a = 1; a< = 1000; a ++){对于(b = a +1; b< = 1000; b ++){c = 1000-a-b;answerFound =确定IfPythagoreanTriple(a,b,c);}}}System.out.println((" + a +," + b +," + c +)");}} 

运行代码时,出现此错误:

  Project_euler9.java:32:错误:变量a可能尚未初始化System.out.println(我们正在寻找的毕达哥拉斯三联体是(" + a +," + b +," + c +)")); 

注意:我为每个变量(a,b和c)使用了不同的行号.

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

即使不是这种情况,在我看来,他们都被分配了,所以我对错误有点困惑.

为什么会这样?

解决方案

实例变量(在您的情况下为 integers )默认分配为 0 .本地变量不是. (来自Java文档)

如果未进入循环,则不会初始化变量,这就是错误的原因.

您可以做的是在声明时将其初始化:

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

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?

解决方案

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;

这篇关于Java变量可能尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆