所以我是Java的新手,大约一个月前,我们才在我的编程课上开始使用这种语言。无论如何,我们现在正在使用重载方法(上周刚刚开始使用方法),而在比较重载方法中的return语句的值时遇到了麻烦。我的意图是在main方法的if语句中对它们进行比较。我敢肯定答案很简单,但是我无法在教科书或在线上找到相关信息。抱歉,草率的缩进使我无法使用该网站上的功能,这是我第一次使用它。将不胜感激!这是程序:
import java.util.Scanner;
public class pizzaCalculation {
public static void main(String[] args){
//create scanner
Scanner i = new Scanner(System.in);
//create sentinel while loop, initiate priceperinch for both pizzas
int sentinel = 1;
//create while loop
while(sentinel != 0){
//create input for round pizza
System.out.println("What is the price of the round pizza?");
double priceRound = i.nextDouble();
System.out.println("What is the radius?");
double radius = i.nextDouble();
pizzaPrice(radius, priceRound);
System.out.println("What is the price of the rectangular pizza?");
double priceRect = i.nextDouble();
System.out.println("What is the width and length of the rectangular pizza?");
double width = i.nextDouble();
double length = i.nextDouble();
pizzaPrice();
//create if statement to determine best deal
if (pricePerInchRound > pricePerInchRect){
System.out.println("The best deal is the round pizza which is $"+pricePerInchRound);
}else{
System.out.println("The best deal is the rectangular pizza is $"+pricePerInchRect);
}
//ask if user would like to do again
System.out.println("Would you like to do another calculation? Enter 1 for yes and 0 for no.");
sentinel = i.nextInt();
}
}
public static double pizzaPrice(double num1, double priceRound){
Scanner i = new Scanner(System.in);
//this is for round pizza
double areaRound = Math.PI * num1 * num1;
double pricePerInchRound = priceRound / areaRound;
return pricePerInchRound;
}
public static double pizzaPrice(double num1, double num2, double priceRect){
//this is for rectangular pizza
//create scanner
Scanner i = new Scanner(System.in);
double areaRect = num1 * num2;
double pricePerInchRect = priceRect / areaRect;
return pricePerInchRect;
}
}
答案 0 :(得分:0)
所以有几个问题:
您需要像这样将参数传递到pizzaPrice()
的第二次调用
pizzaPrice(width, length, priceRect);
您需要将方法调用的结果存储在变量中,例如
pricePerInchRound = pizzaPrice(a, b);
pricePerInchRect = pizzaPrice(a, b, c);
答案 1 :(得分:0)
您正在调用pizzaPrice()
,但需要将结果值存储在变量中,以便以后使用(并传递正确的参数)。
double pricePerInchRound = pizzaPrice(radius, priceRound);
和...
double pricePerInchRect = pizzaPrice(width, length, priceRect);
此外,请小心命名更好的方法参数-num1,num2的描述性不是很好。您本可以使用宽度,长度。