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

How do i get the value of a method to use in main

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

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

    }

}

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

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

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

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

//   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;
    }
}