【问题标题】:Unable to figure runtime error in below code无法在下面的代码中计算运行时错误
【发布时间】:2012-07-19 06:48:38
【问题描述】:

您好,我无法解决以下问题中的运行时错误,请任何人解决

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);
    }
}

【问题讨论】:

  • 你在哪一行得到异常?
  • 当在 Eclipse 中尝试它时它没有给出任何异常,我已将此代码放在在线考试站点中,该站点将编译它,编译后说运行时错误,但不提供哪一行或异常名称
  • 所以在你的电脑上试一试,它会告诉你异常发生在哪一行。我们需要有关该问题的更多详细信息,以便我们为您提供帮助。
  • 嘿,我在我的机器上试过了,它有 eclipse,它没有给出任何异常并且还提供输出
  • 类必须是public。也许这就是问题所在。但是编译器应该抱怨这个......

标签: java


【解决方案1】:

问题在于,如果用户提供带有逗号 (,) 的输入并且逗号是最后一个字符(或唯一的字符),那么 event1 将最多有 1 个元素:event1[0]。元素event1[1] 将不存在,因此您将获得ArrayIndexOutOfBoundsException

仅当输入如下时才会发生这种情况:bgh,afsfgf, 甚至 ,

您可以通过检查数组event1 包含的元素数量来解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多