ArrayIndexOutOfBounds on增强的for循环 [英] ArrayIndexOutOfBounds on enhanced for loop

查看:219
本文介绍了ArrayIndexOutOfBounds on增强的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚任务的一部分,而且我已经在墙上打了一段时间了。我正在尝试将DNA序列转录成RNA序列。但是,我得到一个ArrayOutOfBoundsException。我是新手使用增强型for循环进行迭代,所以我的错误可能隐藏在某处。只有满足if语句参数才会发生。

I am trying to figure out part of an assignment and I have been beating my head against a wall for some time now. I'm trying to transcribe DNA sequences to RNA sequences. I am, however, getting an ArrayOutOfBoundsException. I am new to using enhanced for loops to iterate so my mistake may be hiding in there somewhere. It doesn't occur until the if statement parameters have been met.

private String dnaToRNA(String input) {

    StringBuilder b = new StringBuilder();
    char[] arr = input.toCharArray();
    for (char a : arr) {
        if (a == 'T') {
            arr[a] ='U';

        }
    }   
     for (char a : arr) {
        if (a == 'A'){
            b.append ('U');
        }

        else if (a == 'U') {
            b.append('A');
        }

        else if (a == 'C') {
            b.append('G');
        }   

        else if (a == 'G') {
            b.append('C');
        }   

    }   


    return b.reverse().toString();
}

}

   public void transcribe(int pos1) {

    if (pos1 > linkedList.size()) {
        System.out.println("Position selected out of range");
        return;
    }
    if (linkedList.get(pos1) != null && isValidDNA(linkedList.get(pos1))) {
        linkedList.set(pos1, dnaToRNA(linkedList.get(pos1)));
    }
}


推荐答案

问题出在声明 arr [a] ='U';

问题在于 char 在内部表示为 int 'T'等于84因此你得到 ArrayIndexOutOfBoundsException
您需要使用传统计数器迭代它:

The problem is that char is represented as an int internally and 'T' equals 84 hence you get an ArrayIndexOutOfBoundsException. You need to iterate over it with a traditional counter:

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == 'T') {
        arr[i] ='U';
    }
}   

这篇关于ArrayIndexOutOfBounds on增强的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆