2017-08-02 153 views
0

我有一些代码,第33行返回-1,因为它找不到值。但为什么它没有找到它?我认为这可能与char []有关,但我在这里确实不太确定。这段代码为什么返回-1?

这也可能是因为线路31(INT TEMP),但我真的不知道。

import java.util.Arrays; 
import java.util.HashMap; 
import java.util.Scanner; 

class Main { 

public static void main(String args[]) { 

HashMap<Integer, String> map = new HashMap<Integer, String>(); 

System.out.println("Enter your string to cipher: "); 

Scanner s = new Scanner(System.in); 
String str = s.nextLine(); 

char[] letters = {'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'}; 
Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}; 

if (str instanceof String) { 
    System.out.println("Input received: OK."); 
} else { 
    System.out.println("Error! You cannot input numbers. Exiting program..."); 
    System.exit(1); 
} 

for (int i = 0; i < str.length(); i++) { 
    char l = str.charAt(i); 

    System.out.println(l); 

    int temp = Arrays.asList(letters).indexOf(l); 

    System.out.println(temp); 


    } 


    } 

} 
+1

你可能在你的输入大写字母也决定。 – Zircon

+0

顺便说一句'char'本质上是一个'int',可以例如做'升>“一个” &&升<“z''。 – Rogue

+0

不,甚至如果我做了我可以将它转换为小写,所以不是问题。 – GoldShovel

回答

1

将变量'字母'的类型更改为Character[],它会工作。

奖金小小的优化建议:离开这一行int temp = Arrays.asList(letters).indexOf(l)外循环,因为它是要创建在每次迭代的列表。

,如果你想使用泛型集合使用数组或数组一样char[]

+0

谢谢。你能解释什么字符[]不起作用,但字符[]呢? – GoldShovel

+0

字符是一个对象,而焦炭是一种原始的 所以当的indexOf平等内部测试是测试字符是否等于char这始终是假的,甚至寿你看起来相同的值 – Fminus

+0

非常有意义。我不知道它测试的是字符而不是字符。谢谢。 – GoldShovel