Search code examples
javamethodsreturnprogram-entry-point

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


i'm still pretty new with Java and am trying to write a program that will show me how much my money is actually getting me whenever i make an ingame purchase. I'm struggling with getting the value from the method convertYourself() into my main method so that i can combine them. I think i would most likely need make it a double instead of a void and return it but what would i pass as the parameter? Thank you!

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

    }

}

Solution

  • You would need to have the method to return a value. That can be done like this:

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

    So, you would have to change the method return value from void to double, and use the return keyword to return the value you want.