java - 为什么此代码不断返回“变量可能尚未初始化”错误?
问题描述
我是使用 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.");
}
}
该代码中可能还有其他一些问题,因为我还没有成功运行它,但如果有人能帮助我解决这个问题,我将不胜感激。谢谢!
解决方案
在下面的代码中:
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;
推荐阅读
- azure - 由于权限问题,无法通过 Azure 门户将应用服务证书 (ASC) 导入 Azure Web 应用
- r - 在 Jupyter Lab (irkernel) 中编码 r - 使用 stringr 包:str_view() 函数失败
- python - 如何让不同的方块从屏幕顶部落下
- html - 如何更改 asp.net-core mvc 示例页面中的字体颜色
- python - 如何在 Python 3 中从字符串中删除子字符串
- python-3.x - Selenium 失败,因为 chromedriver 和 google-chrome 版本不兼容,尽管两者版本相同
- javascript - 通过 Javascript 后,我的 URL 混淆了
- html - 如何在设置时自动刷新 html?
- cassandra - Cassandra错误太多未决的远程请求
- php - jQuery Validate:REMOTE 方法永远不会通过验证