2015-07-03 61 views
-2

我有(在这个例子中)两个ArrayList s。明文字母表和加密字母表。我想从明文字母表中取一个字母,并从加密字母表的相应索引中得到该字母。但是,即使条目存在,它始终将索引返回为-1。Java - arraylist1.get(arraylist2.indexOf(nextCharacter))返回-1

public class Rotor { 
    String currentIndex; 
    private ArrayList rotorType = new ArrayList(); 
    private ArrayList control = new ArrayList(); 
    private final char[] alpha = new char[]{ 
     'A', 'B', 'C', 'D', 'E', 'F', 'G', 
     'H', 'I', 'J', 'K', 'L', 'M', 'N', 
     'O', 'P', 'Q', 'R', 'S', 'T', 'U', 
     'V', 'W', 'X', 'Y', 'Z'}; 

    static char[] I = new char[]{ 
     'E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q', 
     'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H', 
     'X', 'U', 'S', 'T', 'A', 'I', 'B', 'R', 
     'C', 'J'}; 

    public Rotor(char[] rotor) { 
     for (int i = 0; i < 25; i++) { 
      rotorType.add(rotor[i]); 
      control.add(alpha[i]); 
     } 
    } 

    public void convert(String nextCharacter) { 
     currentIndex = String.valueOf(rotorType.get(control.indexOf(nextCharacter))); 
    } 
} 

什么会导致此返回索引-1?

+2

“char”值(或者说“Character”值)不是字符串。 –

+1

请勿使用原始类型。 –

+0

请创建一个[MVCE](http://stackoverflow.com/help/mcve)。 – Turing85

回答

0

首先:您使用原始类型,其中you should not do

第二:由于Sotirios Delimanolis指出,Character s不是String s。因此,您不应该询问包含CharacterArrayList,它是否包含String。这会导致问题。

第三:您的字母有26个字符,而不是25个。因此,您的for循环应该迭代为i <= 26,而不是i <= 25

我稍微重写了您的代码,结果似乎是正确的。

import java.util.ArrayList; 

public class Main { 
    String currentIndex; 
    private ArrayList<Character> rotorType = new ArrayList<Character>(); 
    private ArrayList<Character> control = new ArrayList<Character>(); 

    static final char[] alpha = { 
     'A', 'B', 'C', 'D', 'E', 'F', 'G', 
     'H', 'I', 'J', 'K', 'L', 'M', 'N', 
     'O', 'P', 'Q', 'R', 'S', 'T', 'U', 
     'V', 'W', 'X', 'Y', 'Z'}; 

    static final char[] I = { 
     'E', 'K', 'M', 'F', 'L', 'G', 'D', 'Q', 
     'V', 'Z', 'N', 'T', 'O', 'W', 'Y', 'H', 
     'X', 'U', 'S', 'T', 'A', 'I', 'B', 'R', 
     'C', 'J'}; 

    public Main(char[] rotor) { 
     assert (alpha.length == rotor.length) : "rotor must be of same length as alpha."; 
     for (int idx = 0; idx < alpha.length; ++idx) { 
      rotorType.add(rotor[idx]); 
      control.add(alpha[idx]); 
     } 
    } 

    public void convert(char nextCharacter) { 
     currentIndex = String.valueOf(rotorType.get(control.indexOf(nextCharacter))); 
    } 
} 
+0

'for(int i = 0; i <26; i ++)' - 这是硬代码,对不对? – Andrew

+0

@AndrewTobilko是的,从技术上讲,你是正确的查询数组的长度或 - 甚至更好 - 使用foreach循环。但是你也应该断言,两个数组长度相同或者使用两个for循环(每个数组一个)。 – Turing85

+0

我同意你的意见 – Andrew