Java新手 - >方法问题

时间:2014-10-31 16:57:30

标签: java methods call

很确定我在这里遗漏了一些相当明显的东西,但我只是在几天之前就已经这么做了。任何帮助将非常感激。我设法用我想要用来编译的方法来获取我的类,通过我的主要方法,我计划链接我的所有结果都是出错。它说我的实际论点和形式是不同的。我认为我没有将它们连接到其他类或其他东西,但我有点迷失。再次感谢!

public class SphereAndCone {
    public static void main(String[] args) {
        Calc calc1 = new Calc();
        Scanner input = new Scanner(System.in);
        System.out.print("What is the radius?");
        // set sphere/cone radius
        double r = input.nextDouble();
        System.out.print("What is the height?");
        // set sphere/cone height
        double h = input.nextDouble();
        // print results while calling on methods
        System.out.printf("Sphere Volume: %3f16" + calc1.sphereVolume());
        System.out.println();
        System.out.printf("Sphere Surface: %3f16" + calc1.sphereSurface());
        System.out.println();
        System.out.printf("Cone Volume: %3f16" + calc1.coneVolume());
        System.out.println();
        System.out.printf("Cone Surface: %3f16" + calc1.coneSurface());
        System.out.println();
    }
}

1 个答案:

答案 0 :(得分:1)

System.out.printf()方法具有以下签名(String, Object...)(根据JavaDoc)。

现在让我们转到您的代码:

System.out.printf("Sphere Volume: %3f16" + calc1.sphereVolume());

+符号连接两个值。结果将是String,因为第一个参数是String。因此,我们假设calc1.sphereVolume()返回1.0。 VM会将1.0浮点值转换为String,您将获得新创建的"球体积:%3f161.00000000000000" String。当JVM尝试执行printf方法时,它会看到有一个占位符("%3f16")并在varagrs中搜索(Objec...参数)。它看到没有varargs抛出异常。所以基本上就是这样:)

希望这有用:)