.toCharArray方法没有数组的属性

时间:2016-01-24 23:50:35

标签: java arrays

此代码在第7行中一直给出错误:

error: array required, but String found
           switch(str[i]){

似乎没有将创建的数组视为数组......有什么建议吗?

public class Encryption_plus_some{

    public String encrypt(String str){
        String answer = "";
        str.toCharArray();
        for(int i = 0; i < str.length(); i++){
            switch(str[i]){
                case "a": answer += "a";
                    break;
                case "b": answer += "y";
                    break;
                case "c": answer += "x";
                    break;
                case "d": answer += "w";
                    break;
                case "e": answer += "e";
                    break;
                case "f": answer += "u";
                    break;
                case "g": answer += "t";
                    break;
                case "h": answer += "s";
                    break;
                case "i": answer += "i";
                    break;
                case "j": answer += "q";
                    break;
                case "k": answer += "p";
                    break;
                case "l": answer += "o";
                    break;
                case "m": answer += "n";
                    break;
                case "n": answer += "m";
                    break;
                case "o": answer += "o";
                    break;
                case "p": answer += "k";
                    break;
                case "q": answer += "j";
                    break;
                case "r": answer += "i";
                    break;
                case "s": answer += "h";
                    break;
                case "t": answer += "g";
                    break;
                case "u": answer += "u";
                    break;
                case "v": answer += "e";
                    break;
                case "w": answer += "d";
                    break;
                case "x": answer += "c";
                    break;
                case "y": answer += "i";
                    break;
                case "z": answer += "a";
                    break;
                default: answer += " ";
                    break;
            }
        }
        return answer;
    }
    public static void main(String[] args) {
        System.out.println(encrypt("some words to encrypt"));   
    }
}

2 个答案:

答案 0 :(得分:4)

.toCharArray从字符串返回一个char数组(char []),它不会将String值转换为charArray。 String str仍然是一个字符串。

尝试:

char[] charArray = str.toCharArray();

函数无法更改变量的类型。

答案 1 :(得分:0)

将str.toCharArray保存在char数组中

count = 0
list = ['strings','morestrings','12','4334','anotherstring']
for val in list:
    try:
        val = int(val)
        if val < 50:
            count += 1
    except ValueError:
        continue

print(count)