您好我正在尝试做这个功课,我应该编写一个方法,从我写的其他方法中获取一些信息。 (例如汽车类型,日期,演员等)。所以我的问题是,我可以在我的最终方法中使用这些方法的返回值而不再调用它们吗?这是我的主要方法:
public class Homework3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char customer = 'O';
int numberOfCustomers = 0;
int totalEarning= 0;
while(customer != 'N'){
System.out.println("Car Type is " + promptForCarType());
System.out.println("Car rented for " + calculateDays() + " days.");
promptForExtras();
System.out.printf("\nTotal : %d TL",calculateTotal() );
totalEarning += calculateTotal();
numberOfCustomers ++;
System.out.println("Number of customers : " + numberOfCustomers);
System.out.println("Total amount earned : " + totalEarning);
while(customer != 'N' || customer != 'Y'){
System.out.println("A new customer? (Y/N)");
customer = input.next().charAt(0);
customer = Character.toUpperCase(customer);
}
}
}
我应该在我的calculateTotal()方法中使用汽车类型,天数,额外费用。我还尝试将其他方法的返回值分配为变量,并在我的最终方法中将它们用作参数但不起作用。例如我试着写这样的东西:
public static int calculateTotal(){
int total=0;
int time = calculateDays();
int rate = (time / 7)*5 + (time % 7);
if(promptForCarType().equals("Economy"))
total += 50*rate;
else if(promptForCarType().equals("Midsize"))
total += 70*rate;
else if(promptForCarType().equals("Fullsize"))
total += 100*rate;
total += promptForExtras() * time;
return total;
}
但是当我在main方法中调用calculateTotal()时,它会再次自动调用calculateDays()
答案 0 :(得分:1)
基本上,可以做的是将值从calculateDays
传递到calculateTotal
,这样您就不需要再次计算......
System.out.println("Car Type is " + promptForCarType());
in days = calculateDays();
System.out.println("Car rented for " + days + " days.");
promptForExtras();
System.out.printf("\nTotal : %d TL",calculateTotal(days) );
然后您需要更改calculateTotal
以允许它接受您想要传递的值...
public static int calculateTotal(int time){
int total=0;
int rate = (time / 7)*5 + (time % 7);
//...
例如......