将数字数组转换为单词数组

时间:2018-10-22 16:56:02

标签: java string int

例如,我正在尝试将数字数组转换为单词数组:

{1,2}将转换为{"one","two"}

所以这是我在Java中编写的代码:

public static void main(String[] args) {

    ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1,2));

    Integer [] list1Array = list1.toArray(new Integer[0]);
    int numLength2 = list1.size();
    for(int i = 0; i < numLength2; i++){
        System.out.println(list1Array[i]);
     }   
    System.out.println(numLength2);
    String n2 = ""; 
    for(int j = 0; j < numLength2; j++) {
       int element = list1.get(j);
       System.out.println(element);
       switch (element) {
              case '1': {  
                    n2 = n2 + "one";
                    break;
                }
              case '2': { 
                    n2 = n2 + "two";
                    break;
                }

                default: {
                    n2 = n2 + "zero";
                }
            }
        }
        System.out.println(n2);
    }
}

除了最后一次打印,它工作正常:

 System.out.println(n2);

此处的输出为zerozero,而应为onetwo。代码有什么问题?

4 个答案:

答案 0 :(得分:5)

elementint,但是您正在将其与char文字进行比较。您应该改用int文字:

switch (element) {

    case 1: {  
        n2 = n2 + "one";

        break;
    }
    case 2: { 
        n2 = n2 + "two";
        break;
    }

    default: {
        n2 = n2 + "zero";
    }
}

答案 1 :(得分:1)

case '1''1'char类型,但是elementint

答案 2 :(得分:1)

此外,如果更改此行,程序将运行:

int element = '0' + list1.get(j);

答案 3 :(得分:1)

您可以通过这几行代码而不是forloop和switch来实现相同的目的。

public static void main(String[] args) {
    List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 5, 4));
    String[] numArray = { "zero", "one", "two", "three", "four", "five" };

    for (Integer num : list1) {
        System.out.print(numArray[num]);
    }
}

此打印,

onetwofivefour

现在,正如您所说的,您想要创建一个像{“ one”,“ two”}这样的列表,您可以执行以下操作,

public static void main(String[] args) {
    List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 5, 4));
    String[] numArray = { "zero", "one", "two", "three", "four", "five" };
    List<String> wordList = new LinkedList<String>();

    for (Integer num : list1) {
        wordList.add(numArray[num]);
    }
    System.out.println(wordList); // prints [one, two, five, four]
}