将值从一种方法返回到另一种方法以在输出中使用
Returning a value from one method to another to be used in the output
我不知道如何 return 将 finalCost 的值传给 main 方法并打印它。
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
具体来说,我找不到如何在“println”行中使用 returned 值。
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
您调用 calcMonthlyCharge(downloadLimit)
,但不存储返回值。
当你打电话给System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
finalcost 是什么未知,这是一个只存在于 calcMonthlyCharge
范围内的变量
要么存储 calcMonthlyCharge(downloadLimit)
的返回值并重用该值进行打印,要么在 println
中使用 calcMonthlyCharge(downloadLimit)
并使用 downloadLimit 作为参数来获取新的返回值。
我不知道如何 return 将 finalCost 的值传给 main 方法并打印它。
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
具体来说,我找不到如何在“println”行中使用 returned 值。
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
您调用 calcMonthlyCharge(downloadLimit)
,但不存储返回值。
当你打电话给System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
finalcost 是什么未知,这是一个只存在于 calcMonthlyCharge
要么存储 calcMonthlyCharge(downloadLimit)
的返回值并重用该值进行打印,要么在 println
中使用 calcMonthlyCharge(downloadLimit)
并使用 downloadLimit 作为参数来获取新的返回值。