“线程中的异常”;“主要”;java.lang.ArrayIndexOutOfBoundsException:0位于Power.main(Power.java:7)
有人能告诉我哪里出了问题吗?为什么我在标题第7行的内容中收到以下错误消息?我怀疑您运行的类“线程中的异常”;“主要”;java.lang.ArrayIndexOutOfBoundsException:0位于Power.main(Power.java:7),java,Java,有人能告诉我哪里出了问题吗?为什么我在标题第7行的内容中收到以下错误消息?我怀疑您运行的类Power没有命令行arg,这行: public class Power { public static void main (String[]args){ int num = Integer.parseInt(args[0]); int square = (int) Math.pow(num,2); int cube = (int) Math
Power
没有命令行arg,这行:
public class Power {
public static void main (String[]args){
int num = Integer.parseInt(args[0]);
int square = (int) Math.pow(num,2);
int cube = (int) Math.pow(num ,3);
int sqrt = (int) Math.sqrt(num);
System.out.println(num + "squared is" + square);
System.out.println(num + "Cubed is" + cube);
System.out.println(num + "The square root of" + sqrt);
}
}
(尝试读取第一个命令行arg并将其解析为整数)正在爆炸它只是意味着您试图使用无效索引访问数组(对于arr.length>0,有效索引从0到arr.length-1) 在您的例子中,
intnum=Integer.parseInt(args[0])代码>是导致问题的原因
您应该从中传递一个数字作为命令行参数以使其工作。这意味着args[0]中没有任何项,列表为空。程序运行时没有参数,您应该通过执行args.length并确保它不是0进行检查,然后可能会打印一个错误,如果没有传递参数,则需要参数。如果您使用:
int num = Integer.parseInt(args[0]);
您应该在启动应用程序时向函数传递一个参数
int num = Integer.parseInt(args[0]);
是否将参数传递给exe?“args”数组似乎为空。这一行导致了int num=Integer.parseInt(args[0])问题;为了更好地验证,如果您想用程序验证命令行参数,请使用上面的代码。
public static void main (String[]args){
if(args.length ==0) {
System.out.printf("Please pass command line argument e.g Power 10") ;
System.exit(1) ;
}
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
int num = Integer.parseInt(args[0]);
int square = (int) Math.pow(num,2);
int cube = (int) Math.pow(num ,3);
int sqrt = (int) Math.sqrt(num);
System.out.println(num + "squared is" + square);
System.out.println(num + "Cubed is" + cube);
System.out.println(num + "The square root of" + sqrt);
}