【问题标题】:Java: getting an index out of bounds exceptionJava:获取索引越界异常
【发布时间】:2019-12-02 22:47:28
【问题描述】:

背景

在 Java 中构建汇编程序: 我正在尝试将用户的输入读入名为vArrayList。 如果用户输入与String-array table 之一匹配的指令,则将计算相应的操作码并将其输出到文本文件中。

问题

但是,在输入nop指令并尝试添加另一条指令后,我得到了一个索引越界异常

源代码

//Array of instructions 
    String table[] = {"LI", " MALSI", "MAHSI", "MSLSI", "MSHSI", "MALSL", "MAHSL",
        "MSLSL", "MSHSL", "NOP", "A", "AH", "AHS", "AND", "BCW", "CLZ", "MAX", "MIN",
        "MSGN", "MPYU", "OR", "POPCNTH", "ROT", "ROTW", "SHLHI", "SFH", "SFW", "SFHS", "XOR "};
    //Array of binary values of the instructions
    String table2[] = {"0", "10000", "10001", "10010", "10011", "10100", "10101",
        "10110", "10111", "1100000000000000000000000", "1100000001", "1100000010", "1100000011",
        "1100000100", "1100000101", "1100000110", "1100000111", "1100001000", "1100001001",
        "1100001010", "1100001011", "1100001100", "1100001101", "1100001110", "1100001111",
        "1100010000", "1100010001", "1100010010", "1100010011"};
    // TODO code application logic here
    Scanner s = new Scanner(System.in);
    String ins = "";
    String fileName = "outfile.txt";
    System.out.println("Please enter MISP function, enter Q to Quit: ");
    boolean q = true;
    String op = "";
    int c = 0;
    String array[] = new String[64];

    //Loop to keep accepting userinput
    while (q) {
        //accepts the user input 
        ins = s.nextLine();
        //arraylist to hold user input 
        List<String> v = new ArrayList<String>();
        //adds the user input to the arraylist 
        v.add(ins);//user input to nop opcode 
        if (v.get(0).toUpperCase().equals("NOP")) {
            op = "1100000000000000000000000";
        } else if (v.get(1).toUpperCase().equals("LI"))//li opcode 
        {
            String p[] = v[1].split(",", 1);
            op = "0";
            op += toBinary(p[0], 3);
            op += toBinary(p[1], 16);
            op += toBinary(p[2], 5);

我得到了错误堆栈跟踪

线程“主”java.lang.IndexOutOfBoundsException 中的异常:

如果你们能提供帮助,我们将不胜感激。

【问题讨论】:

  • 异常的堆栈跟踪将告诉您失败的确切行。在那之前,我们只能猜测。我猜是您正在访问 v[1] 的 3 个字段,而没有检查是否确实有 3 个字段。
  • 在您的屏幕截图中,所选行 String p[] = v[1].split(",", 1); 引用 List v 就像是一个数组。从来没见过。但同意:您应该检查从split 调用(例如if (p.length == 3) 等)返回的数组的长度。此长度可以为 0 或更大,因此如果随机访问,则会产生越界异常。
  • Same bounds-checking 在使用 List 的方法 size() 访问 List 的元素之前适用(例如,if (v.size() &gt; 2) 在访问 second 元素之前,如 v.get(1) )。
  • 插入您的堆栈跟踪,就像在这个example 中一样,以便我们分析问题。只需edit 并将其粘贴到末尾即可。

标签: java arraylist indexoutofboundsexception


【解决方案1】:

这个循环永远不会结束。

while (q)

【讨论】:

  • 观察力不错。但未验证:如果 OP 内部使用 break;q = false; 之类的语句,循环可以以受控方式结束。此外,这个观察不是答案,所以将这样的观察作为评论发表 :-)
猜你喜欢
  • 2018-11-19
  • 2013-03-30
  • 2013-03-05
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多