You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 14:54:01