如何使用Java将整数数组中的所有偶数元素替换为特殊符号”$”

huangapple go评论104阅读模式
英文:

How to replace all even elements in an integer array with a special symbol "$" using java

问题

我们有一个整数数组,其中所有偶数必须被替换为"$"。

以下是我的代码:

int[] array = {1, 2, 3, 4, 5, 6};
char specialChar = '$';

for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
array[i] = specialChar;
}
}

System.out.println(Arrays.toString(array));


输出结果:[1, $, 3, $, 5, $]
预期输出:[1, $, 3, $, 5, $]
英文:

We have an integer array and all even numbers in that array must be replaced by "$";

Here is my code :

int[] array = {1, 2, 3, 4, 5, 6};
char specialChar = &#39;$&#39;;

for (int i = 0; i &lt; array.length; i++) {
if (array[i] % 2 == 0) {
array[i] = specialChar;
    }
}

System.out.println(Arrays.toString(array));

Output Obtained : [1, 42, 3, 42, 5, 42]
Expected Output : [1, $, 3, $, 5, $]

答案1

得分: 3

我认为你需要将结果数组切换为字符数组。

char specialChar = '$';
int[] array = {1, 2, 3, 4, 5, 6};
char[] result = new char[array.length];

for (int i = 0; i < array.length; i++) {
    if (array[i] % 2 == 0) {
        result[i] = specialChar;
    } else {
        result[i] = (char)(array[i] + '0');
    }
}

System.out.println(Arrays.toString(result));
英文:

I think you need to switch the result array into char array

char specialChar = &#39;$&#39;;
int[] array = {1, 2, 3, 4, 5, 6};
char[] result = new char[array.length];

for (int i = 0; i &lt; array.length; i++) {
    if (array[i] % 2 == 0) {
        result[i] = specialChar;
    } else {
        result[i] = (char)(array[i] + &#39;0&#39;);
    }
}

System.out.println(Arrays.toString(result));

huangapple
  • 本文由 发表于 2023年2月23日 22:54:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定