我是Java的新手,但我仍在尝试了解如何返回值然后检索它。在此任务上,指令是使用getMinutes()将值返回给main方法。然后在calcMeth()上使用该值来获取计算结果。该代码有效,但是当我运行它时,getMinutes()会运行两次。我想知道如何在不两次运行getMinutes()的情况下将getMinutes()的值传递给calcMeth()
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);
}
}
最佳答案
您在getMinutes
方法和main
中调用calcMeth
,我想您只是想从main
方法调用它,并将结果作为参数传递给calcMeth
就像是...
public static void main(String[] args){
int minutes = getMinutes();
sammysMotto2();
calcMeth(minutes);
}
并且您需要更改您的
calcMeth
以允许使用值,例如...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;
有关更多详细信息,请参见Passing Information to a Method or a Constructor