您好,我无法计算出以下问题中的运行时错误,请任何人都可以解决
import java.util.Scanner;
class Solution6 {
public static void main(String[] args)
{
boolean condition = false;
do
{
Scanner scanner = new Scanner(System.in);
String value = scanner.nextLine();
condition = value.equalsIgnoreCase("exit");
if(!condition && value.contains(","))
{
calculate(value);
}
} while (!condition);
}
private static void calculate(String value)
{
final String[] event1 = value.split(",");
int ss = 0;
for ( int i = 0; i < event1[0].length(); ++i )
{
char c = event1[0].charAt( i );
ss += (int) c;
}
int sd = 0;
for ( int i = 0; i < event1[1].length(); ++i )
{
char c = event1[1].charAt( i );
sd += (int) c;
}
System.out.println(ss-sd);
}
}
最佳答案
问题是,如果用户提供带有逗号的输入 (,
) 并且逗号是最后一个字符(或唯一的字符),则 event1
将最多有 1 个元素:event1[0]
。元素 event1[1]
将不存在,因此您会收到 ArrayIndexOutOfBoundsException
。
只有当输入如下时才会发生这种情况:bgh,
,afsfgf,
甚至,
。
您可以通过检查数组 event1
包含的元素数量来解决此问题。
关于java - 无法找出下面代码中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555342/