微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我如何获得要在 main 中使用的方法的值

如何解决我如何获得要在 main 中使用的方法的值

我对 Java 还是很陌生,我正在尝试编写一个程序,当我进行游戏内购买时,它会向我显示我的钱实际上为我带来了多少。 我正在努力从方法 convertYourself() 获取值到我的主要方法中,以便我可以将它们组合起来。 我想我很可能需要将它设为 double 而不是 void 并返回它,但是我将作为参数传递什么? 谢谢!

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();
        test.convertYourself(gemValue);
        test.convertYourself(goldValue);
        // double sum = how do i get the value of the convertYourself method so i can use it here?
        System.out.println("The total value of this bundle is :" + sum);
    }

    public void 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);
        

    }

}

解决方法

您需要有返回值的方法。可以这样做:

public double convertYourself(double x) {
    System.out.println("How many are you buying?");
    double currency = in.nextDouble();
    double convert = currency * x;

    return convert;
}

//To call it:
double valueReturned = convertYourself(gemValue);

因此,您必须将方法返回值从 void 更改为 double,并使用 return 关键字返回您想要的值。

,

对于方法,您可以使用返回类型而不是 void。 然后必须通过 return {value} 返回返回值。

//   return type
//      \/
public double convertYourself (double x) {
  double convert = /* convert */;
  return convert;
}

之后,您可以将输出存储在变量中:

double result = convertYourself (/* x */);
,

更具体的编码部分:

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(); ... you do not need this as the both methods are inside the same class. Make the convertYourself method as *static*. 
        double gemValueConverted = convertYourself(gemValue); // call it without the object 
        double goldValueConverted = convertYourself(goldValue);

        double sum = gemValueConverted + goldValueConverted;
        System.out.println("The total value of this bundle is :" + sum);
    }

    public static double convertYourself(double x) { // made the method static and added return type as double
        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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。