“线程中的异常”;“主要”;java.lang.ArrayIndexOutOfBoundsException:索引1超出长度1的界限
我是编程新手,我下面的代码不会编译,不知道为什么。程序应该接受多个命令行参数,将它们解析为双倍,然后将它们添加到currentBalance。然而,若有一个字符串命令,比如“sub”表示减法,那个么它应该接受该字符串,计算前后的双倍数,然后将其添加到当前余额中。任何帮助都将不胜感激,谢谢“线程中的异常”;“主要”;java.lang.ArrayIndexOutOfBoundsException:索引1超出长度1的界限,java,Java,我是编程新手,我下面的代码不会编译,不知道为什么。程序应该接受多个命令行参数,将它们解析为双倍,然后将它们添加到currentBalance。然而,若有一个字符串命令,比如“sub”表示减法,那个么它应该接受该字符串,计算前后的双倍数,然后将其添加到当前余额中。任何帮助都将不胜感激,谢谢 public static void main(String[] args) throws InterruptedException{ // ends program if no input given
public static void main(String[] args) throws InterruptedException{
// ends program if no input given
if(args.length == 0){
return;
}
// starting balance
double currentBalance = 500;
int location = args.length; //stores count of CLIs into location
int penaltyFlag = 0;
double op1 = 0;
double op2 = 0;
String operator = "";
//Test to make sure that inputs can be parsed, would throw exception if can't parse anything
for(int i = 0; i < location ; i++){
// test to see if next arg is double or operator
// if next arg is an operator then take arg and do operation
if(isValidDouble(args[i]) && isValidOperator(args[i+1])){
//input must be a valid operator to continue here
operator = args[i];
op1 = Double.parseDouble(args[i-1]);
op2 = Double.parseDouble(args[i+2]);
currentBalance += operation(op1, op2, operator);
System.out.println("Your balance: $" + currentBalance);
}
// if next operator is a double, add this arg and continue
else if(isValidDouble(args[i])){
double singleOperand = Double.parseDouble(args[i]);
currentBalance += singleOperand;
System.out.println("Your balance: $" + currentBalance);
} }
publicstaticvoidmain(String[]args)抛出InterruptedException{
//如果没有输入,则结束程序
如果(args.length==0){
返回;
}
//起始平衡
双电流平衡=500;
int location=args.length;//将CLI的计数存储到位置
int penaltyFlag=0;
双op1=0;
双op2=0;
字符串运算符=”;
//测试以确保输入可以被解析,若不能解析任何内容,将抛出异常
对于(int i=0;i在“op2=Double.parseDouble(args[i+2]);”中,表示“i+2”将大于args.length并导致outofbound异常我很确定您会遇到此错误,因为您访问的值超出了args
的范围。我的意思是,在for循环中,您正在从I=0
循环到I
r循环调用的是args[i-1]
,args[i+2]
,以及args[i+1]
这意味着当i
为0(for循环刚刚开始)时,您正在询问args
在args[0-1]
=args[-1]
处的值,这是无效的。关于args[i+2]
和args[i+1]
,当for循环结束且i=location-1
(当i
时的最后一个值),您正在调用args[(location-1)+1]
和args[(location-1)+2]
,这两个值都将计算为args
中不存在的索引,因为您将location
定义为args的长度。下面的图片描述了我的意思:
如果第一个参数传递isValidDouble(),第二个参数传递isValidOperator(),这将是i=0时循环的第一次迭代,此行将尝试索引超出范围:op1=Double.parseDouble(args[i-1]),因为索引变为-1。此外,下一行:op2=Double.parseDouble(args[i+2])如果只提供了2个参数,则将从数组末尾索引。您需要添加更多检查以防止出现这些情况。您的错误是在运行过程中发生的,而不是在编译过程中。IDE或日志是否没有显示错误发生在哪一行代码上?此信息应该可以帮助您自己解决问题。