Dan H. Dan H. - 3 years ago 141
Java Question

Calculating price per square inch of a pizza in Java

I am writing a java program to calculate the area of of a pizza in one method and to calculate the price per square inch of a pizza in another method. I have the area method working, but am not getting any output when I try to calculate the price per square inch. I think it has something to do with calling the area() method in the ppsi method, but I'm not sure exactly what I'm doing wrong or how to correctly call the area method.

import java.util.Scanner;
public class Pizza {

public static void main(String[] args){

System.out.println("What is the size of your pizza in inches?");
System.out.println(area() + " square inches");
System.out.println("What is the price of your pizza?");
System.out.println(ppsi());
}

public static double area(){
Scanner keyboard = new Scanner(System.in);
double diameter = keyboard.nextDouble();
return (diameter / 2) * (diameter / 2) * Math.PI;

}
public static double ppsi(){
Scanner keyboard = new Scanner(System.in);
double price = keyboard.nextDouble();
return((area()) / price);
}

}

Answer Source

In your ppsi method, it calls area, which is going to prompt the user to enter ANOTHER value in AGAIN. Instead, prompt for these values first, then pass them into your method

public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is the size of your pizza in inches?");
    double diameter = keyboard.nextDouble();
    System.out.println(area(diameter) + " square inches");
    double price = keyboard.nextDouble();
    System.out.println("What is the price of your pizza?");
    System.out.println(ppsi(diameter, price));
}

public static double area(double diameter){
    //Scanner keyboard = new Scanner(System.in);
    //double diameter = keyboard.nextDouble();
    return (diameter / 2) * (diameter / 2) * Math.PI;

}
public static double ppsi(double diameter, double price){
    //Scanner keyboard = new Scanner(System.in);
    //double price = keyboard.nextDouble();
    return((area(diameter)) / price);
}

This way, the methods are doing ONE job, not two

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download