首页 > 解决方案 > 为什么此代码不断返回“变量可能尚未初始化”错误?

问题描述

我是使用 java 编码的新手,所以如果我有点不了解情况,请原谅,但我的代码不断为我返回此错误:

Main.java:15: error: variable hold might not have been initialized
        return hold;
               ^


我的代码如下:

public class Main 
{
    public static double calcPostage(double ounces)
    {
        double hold;
        if ((ounces <= 10) && (ounces > 0))
            hold = 3;
        else if (ounces > 10)
            hold = ((ounces-10)*0.15)+3;
        else
            System.out.print("Invalid input.");
        return hold;
    }

    public static void main(String[] args) 
    {
        double hold;
        DecimalFormat form = new DecimalFormat("0.000");
        Scanner input = new Scanner(System.in);
        System.out.print("Enter how heavy your package is in ounces.\n");
        double ounces = input.nextDouble();
        System.out.print("It will cost " + form.format(calcPostage(ounces)) + " to mail your package.");
    }
}

该代码中可能还有其他一些问题,因为我还没有成功运行它,但如果有人能帮助我解决这个问题,我将不胜感激。谢谢!

标签: java

解决方案


在下面的代码中:

public static double calcPostage(double ounces)
{
    double hold;
    if ((ounces <= 10) && (ounces > 0))
        hold = 3;
    else if (ounces > 10)
        hold = ((ounces-10)*0.15)+3;
    else
        System.out.print("Invalid input.");
    return hold;
}

假设,如果“if”和“else if”中的条件都不满足,则-- double type variable hold --不会被初始化。因此,您收到错误:

Main.java:15: error: variable hold might not have been initialized
    return hold;
           ^

所以最好初始化你的变量,给它们分配一个默认值或一个初始值。

做这个 :

double hold = 0.0;

推荐阅读