Return value to the main method in java

advertisements

I'm new in java and i'm still trying to understand how to return a value and then retrieve it. on this task, the instructions were to use getMinutes(), to return a value to the main method. and then use that value on calcMeth(), to get the calculation. The code works, but when I run it, the getMinutes(), gets run twice. i want to know how to pass the value of getMinutes() to calcMeth() without twice running the getMinutes()

package ch3Hw;

import java.util.Scanner;

public class SammysMotto2 {

    public static void main(String[] args){

            getMinutes();
         sammysMotto2();
        calcMeth();

    }

    public static int getMinutes(){  //method 2
        int mins;

        Scanner keyboard = new Scanner (System.in);

        System.out.println("Enter the number of minutes for Rental");
        mins=keyboard.nextInt();
        return mins;
    }

    public static void calcMeth(){  //method 3
        int minS;
        int hourS;  // hours
        int priceH;  // price for hours used
        int remMin;     // minutes over an hour
        int priceMin;   // price of minutes used over an hour
        int totalPrice;

        minS=SammysMotto2.getMinutes(); // anytime i called the method, the method runs again
        hourS=minS/60;
        remMin=minS % 60;
        priceH=hourS*40;
        priceMin=remMin*1;
        totalPrice=priceH+priceMin;
        System.out.println("Total price of rental is $" + totalPrice);

    }

    public static void sammysMotto2(){    //Method 2

        String a  ="SsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSsSs";
        String b="Ss                                              Ss";
        String c="Ss        Sammy makes it fun in the sun.        Ss";

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(b);
        System.out.println(a);

    }

}


You call getMinutes in the main method AND the calcMeth, I think you're suppose to only call it from the main method and pass the result to calcMeth as a parameter

Something like...

public static void main(String[] args){

    int minutes = getMinutes();
    sammysMotto2();
    calcMeth(minutes);

}

And you would need to change your calcMeth to allow for a value to be past to it, for example...

public static void calcMeth(int minS){  //method 3
    int hourS;  // hours
    int priceH;  // price for hours used
    int remMin;     // minutes over an hour
    int priceMin;   // price of minutes used over an hour
    int totalPrice;

    hourS=minS/60;

See Passing Information to a Method or a Constructor for more details