猿问

在switch语句中使用char数据

我试图获得一个case语句,以使用从字符串中提取的char数据将整数添加到整数数组中。


int x = SString.length() - 1;

int[] values = new int[x + 1];

for (int i = 0; i <= x; i++) {

    System.out.println(keyword.charAt(i));

    switch (SString.charAt(i)) {

        case 'a':

            values[i] = 0;

        case 'b':

            values[i] = 1;

        case 'c':

            values[i] = 2;

            System.out.println(values[i]);

    }

}

我对when的预期输出SString = abc是values = {0,1,2}。相反,values = {2,2,2}。


郎朗坤
浏览 467回答 3
3回答

不负相思意

您忘记了break语句,而System.out应该在switch语句之外。&nbsp; &nbsp; String SString = "abc";&nbsp; &nbsp; int x = SString.length() - 1;&nbsp; &nbsp; int[] values = new int[x + 1];&nbsp; &nbsp; for (int i = 0; i <= x; i++) {&nbsp; &nbsp; &nbsp; &nbsp; switch (SString.charAt(i)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 'a':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values[i] = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 'b':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values[i] = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 'c':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values[i] = 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(values[i] + " ");&nbsp; &nbsp; }输出:0 1 2

白衣染霜花

您忘记了每个案例陈述中的中断,因此所有案例都失败了,最终都以 values[i] = 2;switch(SString.charAt(i)){&nbsp; case 'a':&nbsp; &nbsp; values[i] = 0;&nbsp; &nbsp; break; // this one for each&nbsp; case 'b':&nbsp; &nbsp; ...

沧海一幻觉

你忘了break声明。switch (SString.charAt(i)) {case 'a':&nbsp; &nbsp; values[i] = 0;&nbsp; &nbsp; break;case 'b':&nbsp; &nbsp; values[i] = 1;&nbsp; &nbsp; break;case 'c':&nbsp; &nbsp; values[i] = 2;&nbsp;&nbsp;&nbsp; &nbsp; break;}
随时随地看视频慕课网APP

相关分类

Java
我要回答