当我运行我的程序时,我得到了这个:
run:
Planetary DataPlanet Diameter(km) Mass(kg) g(m/s^2)
_________________________________________________
Exception in thread "main" java.util.IllegalFormatPrecisionException: 1
Mercury at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2936)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2684)
at java.util.Formatter.parse(Formatter.java:2528)
at java.util.Formatter.format(Formatter.java:2469)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at GravityV1.diameterr(GravityV1.java:45)
at GravityV1.main(GravityV1.java:73)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
我正在尝试在main方法中显示由静态方法生成的信息。不知何故,当我在main方法中调用它时它没有显示它,我也在尝试计算引力并且它没有识别我的一些变量,比如引力的通用常数,我使重力静态方法高于主要方法并在主要计算方法中声明和初始化万有引力常数。任何帮助将不胜感激。以下是我的代码:
public class GravityV1 {
// title static method
public static void title(){
// title
System.out.printf("%10s", "Planetary Data");
// heading
System.out.println("Planet Diameter(km) Mass(kg) g(m/s^2)");
// create line
System.out.println("_________________________________________________");
}
// months static method
public static void planetss(){
// create months array
String[] planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter",
"Saturn", "Uranus", "Neptune"};
// display planets
System.out.printf("%5s", (Object[]) planets);
}
// diameter static method
public static void diameterr(){
// create array of diameter
double[] diameter = {4880, 12103.6, 12756, 6794, 142984, 120536, 51118,
49532};
// display diameter
System.out.printf("%4.1d", diameter);
}
// mass static method
public static void masss(){
// create array of mass
double[] mass = {3.30E23, 4.869E24, 5.97E24, 6.4219E23, 1.900E27,
5.68E26, 8.683E25, 1.0247E26};
// display mass
System.out.printf("%4.1d", mass);
}
// gravity calculation static method
public static double gravity(double g){
// calculate gravity
g = (G * mass) / Math.pow(diameter / 2, 2);
return g;
}
// main method
public static void main(String args[]){
title();
planetss();
diameterr();
masss();
double G = 6.67384 * Math.pow(10, -11);
}
}
答案 0 :(得分:2)
double
类型的 Format specifier不是d
,而是f
。您应该将printf
方法中的diameterr
语句替换为:
System.out.printf("%4.1f", diameter);