Java如何获取convertYourself方法的返回值并在main方法中使用
你的思路完全正确,只需要做两处简单修改即可实现需求:
1. 修改convertYourself()方法的返回值定义
你原来传入的gemValue、goldValue参数是完全正确的,不需要调整参数,只需要把方法返回值从void改为double,并在计算结束后返回结果即可:
// 把返回值类型从void改成double public double convertYourself(double x) { System.out.println("How many are you buying?"); double currency = in.nextDouble(); double convert = currency * x; System.out.println("The true value of this is: " + convert); // 新增返回计算结果的语句 return convert; }
2. main方法中接收返回值求和
调用方法时直接接收返回值,相加就可以得到总和:
public static void main(String[] args) { TestCode test = new TestCode(); // 接收两次计算的返回值 double gemTotal = test.convertYourself(gemValue); double goldTotal = test.convertYourself(goldValue); double sum = gemTotal + goldTotal; System.out.println("The total value of this bundle is :" + sum); }
完整可运行代码
注意不要忘记在类顶部导入Scanner包:
import java.util.Scanner; public class TestCode { Scanner in = new Scanner(System.in); public static double gemValue = 0.01; public static double goldValue = 0.000004; public static void main(String[] args) { TestCode test = new TestCode(); double gemTotal = test.convertYourself(gemValue); double goldTotal = test.convertYourself(goldValue); double sum = gemTotal + goldTotal; System.out.println("The total value of this bundle is :" + sum); } public double convertYourself(double x) { System.out.println("How many are you buying?"); double currency = in.nextDouble(); double convert = currency * x; System.out.println("The true value of this is: " + convert); return convert; } }
内容的提问来源于stack exchange,提问作者Decline
相关产品推荐
相关产品推荐

