为什么它说变量 fc 可能尚未初始化?
why does it say that variable fc may not have been initialized?
`import java.util.Scanner;
public class Shipping
{
public static void main (String []args)
{
Scanner kb= new Scanner (System.in);
System.out.print("What is the weight of the package in pounds? ");
double wop= kb.nextDouble();
System.out.print("How far is the package being shipped in miles? ");
double d= kb.nextDouble();
double fc;
int sc;
if(d%500 !=0) sc= (int)d/500+1;
else sc = (int)d/500;
if(wop<=2)
fc= 1.10*sc;
else if (wop>2&&wop<=6)
fc= 2.20*sc;
else if (wop>6&&wop<=10)
fc= 3.70*sc;
else if (wop>10)
fc= 3.80*sc;
System.out.print("The final shipping price is $"+fc+"");
}
}`
我一直得到的结果是变量 fc 可能尚未初始化,有人可以帮忙吗
只需将 double fc;
更改为 double fc = 0;
。
您知道 fc
将被赋值,因为 if
语句之一将是 true
,但编译器不知道这一点。你只需要给 fc
一个虚拟值,这样编译器就可以看到当你尝试打印它时它肯定会有一个值。
`import java.util.Scanner;
public class Shipping
{
public static void main (String []args)
{
Scanner kb= new Scanner (System.in);
System.out.print("What is the weight of the package in pounds? ");
double wop= kb.nextDouble();
System.out.print("How far is the package being shipped in miles? ");
double d= kb.nextDouble();
double fc;
int sc;
if(d%500 !=0) sc= (int)d/500+1;
else sc = (int)d/500;
if(wop<=2)
fc= 1.10*sc;
else if (wop>2&&wop<=6)
fc= 2.20*sc;
else if (wop>6&&wop<=10)
fc= 3.70*sc;
else if (wop>10)
fc= 3.80*sc;
System.out.print("The final shipping price is $"+fc+"");
}
}`
我一直得到的结果是变量 fc 可能尚未初始化,有人可以帮忙吗
只需将 double fc;
更改为 double fc = 0;
。
您知道 fc
将被赋值,因为 if
语句之一将是 true
,但编译器不知道这一点。你只需要给 fc
一个虚拟值,这样编译器就可以看到当你尝试打印它时它肯定会有一个值。