[英]Why doesn't my else statement work when I put only 2 inputs?
好的,所以我正在我的会计应用程序上,这是到目前为止的结果:
public class Accounting {
public static void main(String[] args) {
while(true){
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
String[] parts = userinput.split(" ");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
int a = Integer.parseInt(part1);
float r = Float.parseFloat(part2);
int t = Integer.parseInt(part3);
double Total = a*Math.pow(1.0+(r/100.0), t);
String[] result = userinput.split(" ");
if (result.length == 3) {
System.out.println(Total);
} else {
System.out.println("Usage: a r t (a is the amount, r is the rate, and t is the time)");
}
}
}
}
我这样做的目的是,如果用户输入的内容多于3个,它将给出用法提示。 但是,当我输入2个输入时,即使2不等于3,也会出现错误而不是用法提示。
这是错误消息:
线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:Accounting.main(Accounting.java:15)为2
我怎样才能解决这个问题?
编辑:这里我的问题不是数组的一部分不存在,因为只有两个输入,但是它不会给出用法提示。
原因是因为您尝试访问不存在的一部分数组:
String part3 = parts[2];
其中parts.length == 2
我假设您得到索引超出范围错误?
当您只有2个输入时,部件数组的范围为[0..1],因此,当您尝试在此处访问部件[2]时:
String part3 = parts[2];
将引发错误。
“我的问题不是数组的一部分不存在,因为只有两个输入,但是它不会给出使用提示。”
不你错了。 关键是您需要在使用假定长度的数组之前检查数组的长度。 这是一个简单的重新排列,应该可以正常工作(此外,大概您会丢失一些东西,例如退出条件,并尝试从解析中获取NumberFormatException):
Scanner input = new Scanner(System.in);
while(true){
String userinput = input.nextLine();
String[] parts = userinput.split(" ");
// check first
if (parts.length != 3){
System.out.println(
"Usage: a r t (a is the amount, r is the rate, and t is the time)"
);
continue; // skip the computation if the input is wrong
}
String part1 = parts[0]; // these lines WILL throw an error
String part2 = parts[1]; // if you attempt to access elements
String part3 = parts[2]; // of the array that do not exist
int a = Integer.parseInt(part1);
float r = Float.parseFloat(part2);
int t = Integer.parseInt(part3);
double total = a*Math.pow(1.0+(r/100.0), t);
System.out.println(total);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.