功能方法,找到球体的体积

时间:2014-10-29 02:28:26

标签: java

public class Part1
{
    public static void main(String args []) 
    { 
        DecimalFormat df=new DecimalFormat("###.##");
        double v;
        Scanner sc = new Scanner( System.in );
        double radius;
        System.out.println( "Enter radius of the basketball: " ); 
        radius = sc.nextDouble(); 
        System.out.println("The volume of the basketball is " +df.format(v));
    }
    public static int volume (int v)
    {   
        v= ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 ); 
    }
}

基本上,我必须让用户输入篮球的半径,你必须计算篮球的体积。代码运作完美,但我不知道如何在函数方法中做到这一点?

1 个答案:

答案 0 :(得分:3)

我非常确定您需要返回double并将radius作为双重传递给volume方法。您还需要调用该函数并获取。您应该尝试限制变量的词法范围。像,

public static void main(String args[]) {
    DecimalFormat df = new DecimalFormat("###.##");
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter radius of the basketball: ");
    double radius = sc.nextDouble();
    double v = volume(radius);
    System.out.println("The volume of the basketball is " + df.format(v));
}

public static double volume(double radius) {
    return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}