Why does the foreach statement not change the element value?

前端 未结 6 1221

How come the following prints boss and not bass?

String boss = \"boss\";
char[] array = boss.toCharArray();

for(char c : array)
{
 if (c== \'o\')
     c =          


        
6条回答
  •  我寻月下人不归
    2020-11-22 01:15

    You're assigning 'a' to the local variable c, but not to the array element. To make it print bass, you'd need

    for (int i = 0; i < array.length; i++) {
        if (array[i] == 'o') {
            array[i] = 'a';
        }
    }
    

提交回复
热议问题